Java - Store GMT time

二次信任 提交于 2019-12-23 04:38:34

问题


  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:


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.




回答2:


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)



回答3:


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.




回答4:


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



回答5:


For Q3, consider using ZonedDateTime class.



来源:https://stackoverflow.com/questions/847496/java-store-gmt-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!