問題描述
在 java 中,我需要從格式的字符串中創建一個日歷對象:
In java I need to make a Calendar object from a String in the format:
yyyy-MM-dd'T'HH:mm:ss
此字符串將始終設置為 GMT 時間.所以這是我的代碼:
This string will always be set as GMT time. So here's my code:
public static Calendar dateDecode(String dateString) throws ParseException
{
TimeZone t = TimeZone.getTimeZone("GMT");
Calendar cal = Calendar.getInstance(t);
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = date.parse(dateString);
cal.setTime(d);
return cal;
}
然后:
Calendar cal = Calendar.getInstance();
try
{
cal = dateDecode("2002-05-30T09:30:10");
} catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
int month = cal.get(Calendar.MONTH)+1;
我得到以下輸出:
Timezone: GMT+00:00 date: 2002-5-30 time: 7:30:10
您可以看到這是錯誤的,因為提供的時間是格林威治標準時間而不是歐洲中部時間.我認為發生的情況是它認為提供的時間是 CET(這是我當前的時區),因此將時間從 CET 轉換為 GMT,因此從最終結果中減去兩個小時.
Which is as you can see wrong since the time provided is in GMT and not CET. I think what happens is that it think the time provided is in CET (which is my current timezone) and therefore converts the time from CET to GMT and therefore deducts two hours from the final result.
誰能幫我解決這個問題?
Could anyone help me with this?
謝謝
順便說一句:出于不同的原因,我不想使用 JodaTime.
Btw: I do not wish to use JodaTime for different reasons.
推薦答案
這里有一些代碼可以幫助你在解析它們之前設置時區:
Here is some code that could help you out with setting the timzones before parsing them:
// sdf contains a Calendar object with the default timezone.
Date date = new Date();
String formatPattern = ....;
SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
TimeZone T1;
TimeZone T2;
....
....
// set the Calendar of sdf to timezone T1
sdf.setTimeZone(T1);
System.out.println(sdf.format(date));
// set the Calendar of sdf to timezone T2
sdf.setTimeZone(T2);
System.out.println(sdf.format(date));
// Use the 'calOfT2' instance-methods to get specific info
// about the time-of-day for date 'date' in timezone T2.
Calendar calOfT2 = sdf.getCalendar();
我發現的另一個類似問題也可能有所幫助:如何在Java中設置默認時區并控制日期在DB上的存儲方式?
another similar question I found might help too: How to set default time zone in Java and control the way date are stored on DB?
這是一個關于 Java & 的很棒的教程.日期:http://www.tutorialspoint.com/java/java_date_time.htm
Here is a great tutorial on Java & Dates too: http://www.tutorialspoint.com/java/java_date_time.htm
這篇關于解析 ISO 8601 字符串本地日期時間,就像在 UTC 中一樣的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!