16
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
java.util.Date fromDate = cal.getTime();
System.out.println(fromDate);

The above code doesn't print the date in GMT, but rather prints in the local timezone. How do I get a GMT equivalent date from the current date (assuming that the program can run in Japan or SFO)

3 Answers3

22

How about this -

public static void main(String[] args) throws IOException {
    Test test=new Test();
    Date fromDate = Calendar.getInstance().getTime();
    System.out.println("UTC Time - "+fromDate);
    System.out.println("GMT Time - "+test.cvtToGmt(fromDate));
}
private  Date cvtToGmt( Date date ){
    TimeZone tz = TimeZone.getDefault();
    Date ret = new Date( date.getTime() - tz.getRawOffset() );

    // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
    if ( tz.inDaylightTime( ret )){
        Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

        // check to make sure we have not crossed back into standard time
        // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
        if ( tz.inDaylightTime( dstDate )){
            ret = dstDate;
        }
     }
     return ret;
}

Test Result :
UTC Time - Tue May 15 16:24:14 IST 2012
GMT Time - Tue May 15 10:54:14 IST 2012

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
18
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Current DateTime in GMT : " + gmtFormat.format(new Date()));

More generally you can convert to any (valid) time zone this way


See

jmj
  • 237,923
  • 42
  • 401
  • 438
2

Like this SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); ?

RMartins
  • 171
  • 1
  • 1
  • 6