Date Conversion in Java

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.
thomaszhwangAsked:
Who is Participating?
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
for_yanCommented:


  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));

Open in new window


Output:
2011-Dec-10 04:17:29

Open in new window

0
 
for_yanCommented:
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.
0
 
CEHJCommented:
>>
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
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Open in new window

0
 
thomaszhwangAuthor Commented:
Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.