I want to convert a java.util.Date
object to a String
in Java.
The format is 2010-05-30 22:15:52
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
One Line option
This option gets a easy one-line to write the actual date.
Please, note that this is using
Calendar.class
andSimpleDateFormat
, and then it's not logical to use it under Java8.
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
Why don't you use Joda (org.joda.time.DateTime)? It's basically a one-liner.
Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
// output: 2014-11-14 14:05:09
Try this,
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Date
{
public static void main(String[] args)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = "2013-05-14 17:07:21";
try
{
java.util.Date dt = sdf.parse(strDate);
System.out.println(sdf.format(dt));
}
catch (ParseException pe)
{
pe.printStackTrace();
}
}
}
Output:
2013-05-14 17:07:21
For more on date and time formatting in java refer links below
Oracle Help Centre
Date time example in java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = "2010-05-30 22:15:52";
java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
System.out.println(sdf.format(formatedDate)); // the use of format function returns a String