Saturday, 17 September 2011

Utilize date in JSON on Java

The date format in Java is frequently used but it is not a basic format in Java. There is an easy way to convert it to java.

1. Create Date
The date format in java has several constructors. The most useful for us is the follow one:
public Date (long date)

This constructor accepts a parameter of type Long which is the milliseconds since January 1st. 1970, 00:00:00 GMT. This date is known as "The epoch" for the unix machines.
Because the long is one of the basic type of JSON, there won't be any problem to use it between the server and the client.

2. Obtain the current time
In Java is very easy to obtain the current time regarding "The epoch" by utilizing the follow method:
System.currentTimeMillis() 

3. Get the milliseconds regarding "The epoch"
If you want to get the milliseconds of a specific time regarding "The epoch", there is a methods of Date for it:
long getTime()

For example:
System.out.println(System.currentTimeMillis());
Date now = new Date(System.currentTimeMillis());
System.out.println("Now " + now);
System.out.println(now.getTime());


The output is:
1316369204630
Now Sun Sep 18 20:06:44 CEST 2011
1316369204630


For more information:
Date (Java 2 Platform SE v1.4.2): http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#Date(long)
Unix Time: http://en.wikipedia.org/wiki/1_January_1970
Check the current milliseconds regarding "The epoch": http://www.epochconverter.com/

No comments:

Post a Comment