Question

This is both a duplicate and not a duplicate!

Just please help me and don't refer me to anywhere else, cause I'm really unable to get the GMT time. The answer seems easy but it doesn't work for me. I don't know are the answers all aver the web wrong, or am I making a mistake?

Please take a look at this snippet and the results:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long time = cal.getTimeInMillis();
Date date = new Date(time);
System.out.println(date);

time = System.currentTimeMillis();
date = new Date(time);
System.out.println("--\n" + date);

result :

Fri Feb 28 16:07:12 GMT+03:30 2014
--
Fri Feb 28 16:07:12 GMT+03:30 2014

Both show my local time. I even printed directly the time, cause I thought maybe this is due to Date class but even those are the same (with just about 1 or 2 milliseconds difference).

Was it helpful?

Solution

Use setTimeZone() on a SimpleDateFormat to print the date in a specific timezone.

DateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss z");

Date d = format.parse("28-Feb-2014 13:00:00 PST");
System.out.println(format.format(d));

format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.format(d));

Prints:

28-Feb-2014 13:00:00 PST
28-Feb-2014 21:00:00 GMT

OTHER TIPS

Try the below

SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(f.format(new Date(System.currentTimeMillis())));

One way of doing it is using SimpleDateFormat and the setTimeZone method():

SimpleDateFormat sdf = new SimpleDateFormat( "..." );
sdf.setTimeZone( TimeZone.getTimeZone( "GMT" ) );   // or UTC
System.out.println( sdf.format( date ) );

Cheers,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top