如何在Java中获取您的时区的当前日期和时间? [英] How to get the current date and time of your timezone in Java?
问题描述
我的应用程序托管在伦敦服务器中。我在西班牙马德里。所以时区是-2小时。
I have my app hosted in a London Server. I am in Madrid, Spain. So the timezone is -2 hours.
如何使用我的时区获取当前日期/时间。
How can I obtain the current date / time with my time zone.
Date curr_date = new Date(System.currentTimeMillis());
例如。
Date curr_date = new Date(System.currentTimeMillis("MAD_TIMEZONE"));
Joda-Time
With Joda-Time
DateTimeZone zone = DateTimeZone.forID("Europe/Madrid");
DateTime dt = new DateTime(zone);
int day = dt.getDayOfMonth();
int year = dt.getYear();
int month = dt.getMonthOfYear();
int hours = dt.getHourOfDay();
int minutes = dt.getMinuteOfHour();
推荐答案
日期
总是基于UTC ...或时区中立,具体取决于您希望如何查看它。 日期
仅表示某个时间点;它独立于时区,距离Unix时代只有几毫秒。没有 Date
的本地实例的概念。将 Date
与 日历
和/或 TimeZone.getDefault()
使用本地时区。使用 TimeZone.getTimeZone(Europe / Madrid)
来获取马德里时区。
Date
is always UTC-based... or time-zone neutral, depending on how you want to view it. A Date
only represents a point in time; it is independent of time zone, just a number of milliseconds since the Unix epoch. There's no notion of a "local instance of Date
." Use Date
in conjunction with Calendar
and/or TimeZone.getDefault()
to use a "local" time zone. Use TimeZone.getTimeZone("Europe/Madrid")
to get the Madrid time zone.
...或者使用 Joda Time ,这将使整个事情更加清晰,IMO。在Joda Time中,您将使用 DateTime
值,该值是特定日历系统和时区中的即时时间。
... or use Joda Time, which tends to make the whole thing clearer, IMO. In Joda Time you'd use a DateTime
value, which is an instant in time in a particular calendar system and time zone.
在Java 8中,你使用 java.time.ZonedDateTime
,这相当于Joda Time的 DateTime
。
In Java 8 you'd use java.time.ZonedDateTime
, which is the Java 8 equivalent of Joda Time's DateTime
.
这篇关于如何在Java中获取您的时区的当前日期和时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!