,以顯示可再現的情況下不工作,我做了以下的Java轉換GMT/UTC到當地時間預期
獲取當前系統時間(本地時間)
將當地時間轉換爲UTC //工作成功直到此處
將UTC時間反轉回當地時間。遵循3種不同的方法(下面列出),但所有3種方法僅保留UTC時間。
{
long ts = System.currentTimeMillis(); Date localTime = new Date(ts); String format = "yyyy/MM/dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat (format); // Convert Local Time to UTC (Works Fine) sdf.setTimeZone(TimeZone.getTimeZone("UTC")); Date gmtTime = new Date(sdf.format(localTime)); System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:" + gmtTime.toString() + "-" + gmtTime.getTime()); // Reverse Convert UTC Time to Locale time (Doesn't work) Approach 1 sdf.setTimeZone(TimeZone.getDefault()); localTime = new Date(sdf.format(gmtTime)); System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:" + gmtTime.toString() + "-" + gmtTime.getTime()); // Reverse Convert UTC Time to Locale time (Doesn't work) Approach 2 using DateFormat DateFormat df = new SimpleDateFormat (format); df.setTimeZone(TimeZone.getDefault()); localTime = df.parse((df.format(gmtTime))); System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:" + gmtTime.toString() + "-" + gmtTime.getTime()); // Approach 3 Calendar c = new GregorianCalendar(TimeZone.getDefault()); c.setTimeInMillis(gmtTime.getTime()); System.out.println("Local Time " + c.toString());
}
一個很好的答案!但是,應該有TimeZone.getDefault()。getOffset(gmtTime.getTimeInMillis()))而不是TimeZone.getDefault()。getOffset(localTime.getTime())。否則,如果您的UTC時間爲冬季,但夏令時爲夏令時,則可能會遇到DaylightSaving的問題。 – Dime
'新的日期(字符串字符串)'已棄用:( –
你是一個救生員T_T這是唯一的方法來解決衝突java.util.date(@temporal)和timestamp(postgresql)的GMT與UTC – Sarief