How to get the current time in GMT?

user353682 picture user353682 · Jun 8, 2010 · Viewed 27.5k times · Source

Possible Duplicate:
How can I get the current date and time in UTC or GMT in Java?

I want to get the current timestamp in GMT; any ideas how to do that?


i managed to get a string in gmt format the problem is that i want to convert this string to equivalent timestamp object i.e same time but as a timestamp object

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date=new Date();
        String s=sdf.format(date);
        System.out.println("GMT: "+s);
        //need to convert the string to equivalent timestamp object

Answer

Mark Peters picture Mark Peters · Jun 8, 2010
new Date().getTime();

Or just

System.currentTimeMillis();

Both assume you take "timestamp" to mean "milliseconds from the Unix epoch". Otherwise, clarify your question.

Edit: In response to the comment/clarification/"answer":

You're misunderstanding the difference between storing a GMT timestamp and displaying it as such. Date/Timestamp will store as milliseconds from the UTC epoch internally, and is not related to a certain timezone, since timestamps are the same regardless of your timezone. If it's 10pm GMT in Honolulu, it's also 10pm GMT in New York. They have the same timestamp, though your location might make them render differently.

A Calendar, on the other hand, is meant for displaying certain fields properly (as in, it's 6pm on the 8th of June) and so does have an internal notion of TimeZone (since 6pm EDT is NOT the same time as 6pm PDT).

Anyway, your example gave a SimpleDateFormat. If you want to display your already-GMT Timestamp in GMT, do the same thing and pass in the Timestamp.

    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss.SS");
    fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println(fmt.format(timestamp));