如何使Date与地区无关? [英] How to make Date locale-independent?
问题描述
我有一个数据库,它以GMT时区以OleDateTime
格式存储日期.我实现了一个类,在Java中扩展了Date
,以经典的日期格式表示该类.但是我的课程是与语言环境相关的(我在GMT + 2中).因此,它将db中的日期转换为date - 2 hours
.如何使其正确转换日期?我希望我的班级始终与区域设置无关,始终使用GMT时区.实际上,问题是:
I have a db, that stores dates in OleDateTime
format, in GMT timezone. I've implemented a class, extending Date
in java to represent that in classic date format. But my class is locale-dependent (I'm in GMT+2). Therefore, it converts the date in the db as date - 2 hours
. How do I make it convert the date correctly? I want my class to be locale-independent, always using GMT timezone. Actually, the question is:
class MyOleDateTime extends Date {
static {
Locale.setDefault(WhatGoesHere?)
}
// ... some constructors
// ... some methods
}
推荐答案
好吧,最好像其他答案中所建议的那样使用Calendar对象.但是,如果您真的要设置全局时区,则可以在应用程序代码的早期使用TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
.还有user.timezone
Java系统属性.
Well, it's better to use the Calendar object like suggested in other answers. However, if you really want to set global timezone, you can use TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
early in your application code. There is also user.timezone
Java system property.
另外(只是很有趣),看来按格林尼治标准时间/世界标准时间(不夏令时更改)实际居住的唯一国家是利比里亚.
Also (just fun to know), it appears that the only country actually living by GMT/UTC time (without daylight saving changes) is Liberia.
实际上,Date
个对象本身总是 与语言环境和时区无关.它的getTime()
方法将始终返回UTC 中自1970年1月1日00:00:00以来经过的毫秒数(不计算leap秒).但是,如果您想获得毫秒以外的其他信息,则必须使用Calendar
,它与时区相关.但这是正确的方法.您不会在Date
类中使用不赞成使用的方法,对吗?
In fact, Date
objects per se are always locale- and timezone-independent. Its getTime()
method will always return the number of milliseconds passed since January 1, 1970 00:00:00 (not counting leap seconds) in UTC. But if you want to get something else than milliseconds, you have to use Calendar
, which is timezone-dependent. But it is the right way to go. You don't use that deprecated methods in Date
class, do you?
这篇关于如何使Date与地区无关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!