tags:

views:

1107

answers:

4

Hi, i have a question:

  1. My server has GMT+7, so if i move to another server has another GMT timezone, all date stored in db will incorrect?
  2. Yes Q1 is correct, how about i will store date in GMT+0 timezone and display it in custom GMT timezone chosen by each member
  3. How i get date with GMT+0 in java
+1  A: 

By default when you get a date in java its in your current timezone, you can use the TimeZone class to get the timezone your system time is running in. Most databases supports that dates can be stored WITH timezone, which probably would be the right way to do this, but exactly what the format is can be dependant on which database you use.

takete.dk
+8  A: 

1) To quote from the javadocs, Java millisecond timestamps are

the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

Therefore, as the timestamp is UTC/GMT, if you store it in the database this date will be correct no matter the time zone of the server.

2) Formatting the timestamp for display depending on the timezone would be the correct approach.

3) Creating a new java.util.Date instance and calling getTime() will get you the timestamp for GMT+0 in Java.

Mark
A: 

To add to mark's point, once you have a java.util.Date, you can "convert" it to any Timezone (as chosen by the User). Here's a code sample in Groovy (will work in Java with slight mods):

// This is a test to prove that in Java, you can create ONE java.util.Date
// and easily re-display it in different TimeZones
fmtStr = "MM/dd/yyyy hh:mm aa zzz"
myDate = new java.util.Date()
sdf = new java.text.SimpleDateFormat(fmtStr)

// Default TimeZone
println "Date formatted with default TimeZone: " + sdf.format(myDate)

// GMT
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
println "Date formatted with GMT TimeZone: " + sdf.format(myDate)

// America/New_York
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"))
println "Date formatted with America/New_York TimeZone: " + sdf.format(myDate)

// PST
sdf.setTimeZone(TimeZone.getTimeZone("PST"))
println "Date formatted with PST TimeZone: " + sdf.format(myDate)
NotWally
A: 

I would suggest that you use Date only as a "holder" and propose that you use Calendar instances instead. To get a Calendar in the GMT time zone just use this:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+00"))

A Calendar will provide a great deal of benefit when you work with times and dates. For instance, adding an hour to this is simple:

cal.add(Calendar.HOUR, 1);

Lastly, when you need a Date you just use this:

Date date = cal.getTime();
Mondain