如何在 Java 中获取时区的当前日期和时间? [英] How to get the current date and time of your timezone in Java?

查看:53
本文介绍了如何在 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

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.

这篇关于如何在 Java 中获取时区的当前日期和时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆