HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

Convert java.util.Date to String

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
javadateconvertutilstring

Problem

I want to convert a java.util.Date object to a String in Java.

The format is 2010-05-30 22:15:52

Solution

Convert a Date to a String using DateFormat#format method:

String pattern = "MM/dd/yyyy HH:mm:ss";

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);

// Get the today date 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 todayAsString = df.format(today);

// Print the result!
System.out.println("Today is: " + todayAsString);


From http://www.kodejava.org/examples/86.html

Code Snippets

String pattern = "MM/dd/yyyy HH:mm:ss";

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);

// Get the today date 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 todayAsString = df.format(today);

// Print the result!
System.out.println("Today is: " + todayAsString);

Context

Stack Overflow Q#5683728, score: 853

Revisions (0)

No revisions yet.