In Java, Convert a Date to a String using a format string:
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// Get the date today using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String reportDate = df.format(today);
// Print what date is today!
System.out.println("Report Date: " + reportDate);
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
In Java, Convert a Date to a String using a format string:
From http://www.kodejava.org/examples/86.html
Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)
Why don't you use Joda (org.joda.time.DateTime)? It's basically a one-liner.
The easiest way to use it is as following:
where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date
output: Sun Apr 14 16:11:48 EEST 2013
Notes: HH vs hh - HH refers to 24h time format - hh refers to 12h time format
If you only need the time from the date, you can just use the feature of String.
This will automatically cut the time part of the String and save it inside the
timeString
.