Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java.util.Date to String

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

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

like image 863
novicePrgrmr Avatar asked Apr 16 '11 00:04

novicePrgrmr


People also ask

How do I change the date format in Java Util?

// Setting the pattern SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy"); // myDate is the java. util. Date in yyyy-mm-dd format // Converting it into String using formatter String strDate = sm. format(myDate); //Converting the String back to java.

Why you should not use Java Util date?

Some other problems are: It rates years as two digits since 1900. There are many workarounds in the Java world around this banal design decision, like handling years before 1900. Months are zero indexed (0 – January, 11 – December).


1 Answers

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

like image 161
Ali Ben Messaoud Avatar answered Oct 11 '22 11:10

Ali Ben Messaoud