本文介紹了SimpleDateFormat getHors()返回不正確的值的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
為什么”09:50″的getHour()返回8?
代碼:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse("09:50");
int hours = date.getHours(); // return 8 instead of 9 ???
推薦答案
您的SimpleDateFormat可能尚未設(shè)置為默認(rèn)時(shí)區(qū)。
呼叫:
sdf.setTimeZone(TimeZone.getDefault());
在解析文字之前,應(yīng)該可以解決您的問(wèn)題。
我測(cè)試了以下代碼:
...
public static final SimpleDateFormat CDfTimestamp = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
...
Date da1 = null;
for (String dl1 : new String[] { "1970-01-01 12:34:56",
"2016-01-01 12:34:56" }) {
try {
CDfTimestamp.setTimeZone(TimeZone.getTimeZone("GMT+05:00"));
da1 = CDfTimestamp.parse(dl1);
System.out.printf("parse GMT+05:00 %s -> %d %d %d (os=%d)
", dl1, da1
.getHours(), da1.getMinutes(), da1.getSeconds(), CDfTimestamp
.getTimeZone().getOffset(0));
CDfTimestamp.setTimeZone(TimeZone.getTimeZone("UTC"));
da1 = CDfTimestamp.parse(dl1);
System.out.printf("parse UTC %s -> %d %d %d (os=%d)
", dl1, da1
.getHours(), da1.getMinutes(), da1.getSeconds(), CDfTimestamp
.getTimeZone().getOffset(0));
CDfTimestamp.setTimeZone(TimeZone.getDefault());
da1 = CDfTimestamp.parse(dl1);
System.out.printf("parse default %s -> %d %d %d (os=%d)
", dl1, da1
.getHours(), da1.getMinutes(), da1.getSeconds(), CDfTimestamp
.getTimeZone().getOffset(0));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
...
獲取以下輸出:
parse GMT+05:00 1970-01-01 12:34:56 -> 8 34 56 (os=18000000)
parse UTC 1970-01-01 12:34:56 -> 13 34 56 (os=0)
parse default 1970-01-01 12:34:56 -> 12 34 56 (os=3600000)
parse GMT+05:00 2016-01-01 12:34:56 -> 8 34 56 (os=18000000)
parse UTC 2016-01-01 12:34:56 -> 13 34 56 (os=0)
parse default 2016-01-01 12:34:56 -> 12 34 56 (os=3600000)
這篇關(guān)于SimpleDateFormat getHors()返回不正確的值的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,