這就涉及要各種本地時間轉UTC時間,UTC時間轉本地時間的問題了。
在這裏必須說的一點就是,不管是服務器間通信,還是瀏覽器或者客戶端與服務器間通信,都採用傳參爲utc時間+時區的方法,而且出於本人習慣,utc時間通常用字符串,方便傳值,也因爲字符串是沒有任何時區瓜葛,是實實在在的。
2.想必大家都聽過太多次 Date中不包含時區的說法,但是當我們這樣寫,想將一個UTC字符串轉換成對應的Date時:
String dateStr = "2013-1-31 12:17:14"; //頁面傳進來的UTC時間
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date dateTmp = dateFormat.parse(dateStr);
System.out.println(dateTmp);
} catch (ParseException e) {
e.printStackTrace();
}
卻發現打印出來是Thu Jan 31 12:17:14 CST 2013 和傳入的字符串一致。 在我轉換成UTC時間時,居然,減少了8個小時。也就是說我的UTC時間跟傳進來的字符串完全不一樣了。
趕緊百度查CST,確發現 CST可視爲美國,澳大利亞或中國的標準時間 在這裏,也就是說是中國標準時間的意思,那麼所謂的不帶時區呢,沒想到你是這樣的Date!
嗯,經過各種亂查,發現其實dateFormat有設置時區的功能,如果在上述第二行代碼下加入這句話:
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
// dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
獲取的Date再轉換成UTC時間,與傳進來的字符串一致。
我理解上面這句代碼的意思爲:告訴別人我的字符串是utc時間
那麼同理,想要把Date轉成對應的UTC字符串,要這樣:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 告訴別人我要的字符串是utc時間
String str = sdf.format(date);
當然偶爾還有將UTC時間的字符串轉換成瀏覽器/客戶端的字符串的需求,這裏一併寫在下面。
/**
* 將utc的字符串轉換成本地Date
*/
public static Date getUTCStrToLocalDate(String s) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 告訴別人我的字符串是utc時間
return sdf.parse(s);
}
/**
* 將Date變成UTC字符串
*/
public static String getUTCStrToLocalDate(Date d) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 告訴別人我的字符串是utc時間
return sdf.format(d);
}
/**
* 將UTC字符串變成瀏覽器端的相應時區的字符串
*/
public static String getUTCStrToBrowserStr(String s, String timeZone)throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 告訴別人我的字符串是utc時間
Date date = sdf.parse(s);
sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); // 告訴別人我的字符串是utc時間
return sdf.format(date);
}