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:

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:
Date now = new Date(System.currentTimeMillis());
System.out.println("Now " + now);

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

For more information:
Date (Java 2 Platform SE v1.4.2):
Unix Time:
Check the current milliseconds regarding "The epoch":

No comments:

Post a Comment