Thursday, 18 October 2012

Java : Date Formats

Common Questions with Date Format

1. What are the possbile date formats?
2. Can I use any delimiter?

I couldn't find a concrete explanation of the possible date formats but I decided to write one based on trial and and error.

Date dateNow = new Date();

a.
System.out.println(dateNow);
Output: Fri Oct 19 09:26:59 CST 2012

b.
String dateStr = new SimpleDateFormat("MMM/dd/yyyy").format(dateNow);
System.out.println(dateStr);
Output: Oct/19/2012

Use MMM to get Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec

Note: If the output month is not in the format "Oct", you can try adding Locale.ENGLISH:
String df = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH).format(dateNow);

c.
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(dateNow);
System.out.println(dateStr);
Output: 2012-10-19 

d.
String dateStr  = new SimpleDateFormat("yyyy/mm/dd").format(dateNow);
System.out.println(dateStr);
Output: 2012/38/19

Note : In letter D, the output is supposedly 2012/10/19. However, you are using the format "yyyy/mm/dd". The month variable should be in capitals, MM instead of mm.
Note : Also make sure that your year variable are in small letters, yyyy instead of YYYY. It will return an error.

As you can see, the format can be interchangeable.

2. Can I use any delimiter? Yes.

0 comments:

Post a Comment