Asked  7 Months ago    Answers:  2   Viewed   30 times

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

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

 Answers

32

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

Tuesday, June 1, 2021
 
Hexaholic
answered 7 Months ago
52

The following only has an overhead for the conversion of the old Date to the new LocalDate.

    Date date = new Date();
    LocalDate ldate = LocalDate.from(date.toInstant().atZone(ZoneOffset.UTC));
    String s = DateTimeFormatter.ISO_DATE.format(ldate); // uuuu-MM-dd

It is true however that DateTimeFormatters are thread-safe and hence will have one instantiation more per call.

P.S.

I added .atZone(ZoneOffset.UTC) because of a reported exception, and @Flown's solution: specifying the zone. As Date is not necessarily used for UTC dates, one might use another one.

Saturday, October 30, 2021
 
Ravinder Kumar
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share