問(wèn)題描述
以下作品(顯示UTC時(shí)間)
The following works (shows UTC time)
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println(new Date());
但這不(顯示當(dāng)?shù)貢r(shí)間)
but this doesn't (shows local time)
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal.getTime());
System.out.println(new Date());
有什么簡(jiǎn)單的東西我錯(cuò)過(guò)了嗎?
Is there something simple, that I'm missing?
推薦答案
您正在打印 Date.toString()
,總是使用默認(rèn)時(shí)區(qū).
You're printing out the result of Date.toString()
, which always uses the default time zone.
我建議你使用 DateFormat
相反,它更適合格式化日期.Date.toString
實(shí)際上只適用于調(diào)試 - 它無(wú)法控制格式.
I suggest you use DateFormat
instead, which is better suited for formatting dates. Date.toString
is really only suitable for debugging - it provides no control over the format.
或者,使用 Joda Time 進(jìn)行所有日期和時(shí)間操作 - 這是一個(gè)更好的 API 開(kāi)始:)
Alternatively, use Joda Time for all your date and time operations - it's a much better API to start with :)
這篇關(guān)于Java Calendar:獲取時(shí)區(qū)時(shí)間的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!