如何在 Java 中获取时区的当前日期和时间?

2022-01-16 00:00:00 timezone java jodatime

我的应用托管在伦敦服务器中.我在西班牙马德里.所以时区是-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

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();

推荐答案

Date 总是 基于 UTC...或时区中性,具体取决于您如何查看.一个 Date only 代表一个时间点;它与时区无关,距 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,它是 Java 8 中 Joda Time 的 DateTime 的等效项.

In Java 8 you'd use java.time.ZonedDateTime, which is the Java 8 equivalent of Joda Time's DateTime.

相关文章