Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeZone problem in Java

Tags:

java

timezone

I am trying to instantiate GregorianCalendar with TimeZone GMT, but whenever I call the getTime() method, it gives me time in local TimeZone. Here is my code:

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
System.out.println(cal.getTime());

The output I am getting is this:

Sat Nov 28 19:55:49 PKT 2009

Please help!

like image 885
craftsman Avatar asked Nov 28 '09 14:11

craftsman


People also ask

How does Java handle time zone issues?

If you cannot change the OS or the JVM timezone, you can still convert a Java Date/Time or Timestamp to a specific time zone using the following two JDBC methods: PreparedStatement#setTimestamp(int parameterIndex, Timestamp x, Calendar cal) – to convert the timestamp that goes to the database.

How do I set the TimeZone in Java?

You can explicitly set a default time zone on the command line by using the Java system property called user. timezone . This bypasses the settings in the Windows operating system and can be a workaround.

How does Java determine TimeZone?

The getDefault() method of TimeZone class in Java is used to know the default TimeZone for this system or host. This may vary in according to the implementation in different environment. Parameters: The method does not take any parameters. Return Value: The method returns the default TimeZone of the host.

What is TimeZone in Java?

TimeZone represents a time zone offset, and also figures out daylight savings. Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time.


1 Answers

I'm not sure if this answers your question, but this is one way to get "now" in GMT.

import java.text.*
import java.util.* 

Calendar cal = new GregorianCalendar();
Date date = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(formatter.format(date));

See the Javadoc on SimpleDateFormat for different patterns. Also, you may want to consider Joda Time as it is far superior for dates and times.

like image 80
Michael Easter Avatar answered Sep 19 '22 10:09

Michael Easter