Clicky

I have a java.util.Date value in local time zone.

What's the most efficient way to convert this value to java.sql.Date in GMT?

Thanks.

asked 12/09/2011 12:10

thomaszhwang's gravatar image

thomaszhwang ♦♦


7 Answers:


1:
2:
3:
4:
5:
6:
7:
8:
java.util.Date dd = new java.util.Date();

        java.sql.Date dd1 = new java.sql.Date(dd.getTime());

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

        System.out.println(dateFormatGmt.format(dd1));


Output:
link

answered 2011-12-09 at 20:17:02

for_yan's gravatar image

for_yan

in this link
http://stackoverflow.com/questions/1516213/java-util-date-is-using-timezone

read this in the answer:

java.util.Date is timezone-independent. Says so right in the javadoc.  

You want something with respect to a particular timezone? That's java.util.Calendar.

The tricky part? When you print this stuff (with java.text.DateFormat or a subclass), that involves a Calendar (which involves a timezone). See DateFormat.setTimeZone().

It sure looks (haven't checked the implementation) like java.util.Date.toString() goes through a DateFormat. So even our (mostly) timezone-independent class gets messed up w/ timezones.

Want to get that timezone stuff out of our pure zoneless Date objects? There's Date.toGMTString(). Or you can create your own SimpleDateFormatter and use setTimeZone() to control which zone is used yourself.
link

answered 2011-12-09 at 20:18:37

for_yan's gravatar image

for_yan

>>
I have a java.util.Date value in local time zone.

What's the most efficient way to convert this value to java.sql.Date in GMT?
>>

A Date object is essentially just a number. Insofar that it's connected with timezones at all, it owns a TimeZone object but that's for internal use. You can think of a Date as just a number - an offset from the 'epoch'. It has no time zone
1:
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
link

answered 2011-12-09 at 20:30:20

CEHJ's gravatar image

CEHJ

Thanks.
link

answered 2011-12-10 at 02:55:33

thomaszhwang's gravatar image

thomaszhwang

Your answer
[hide preview]

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Tags:

×1

Asked: 12/09/2011 12:10

Seen: 219 times

Last updated: 12/14/2011 02:48