Tuesday, 14 October 2008

Java Output Formatted Date String Using SimpleDateFormat

This is another quickie simple example, as it took me ages to find what exactly what I was looking for. :-)

Using Java, I wanted to output the current date as a string, in a particular format. However (with limited knowledge) looking at the obvious starting point of java.util.Date, I couldn't find anything other than the default output.

I now know that this is because java.util.Date doesn't do this, you need to use another class, such as java.text.SimpleDateFormat.

So to output the date as year month day EG "2008-10-14"...
SimpleDateFormat formatNow = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("=Now=> "+formatNow.format(new Date()));

See here for all the format options.


No comments: