How to get the current date and time of your timezone in Java?(如何在 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 中获取时区的当前日期和时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中获取时区的当前日期和时间?
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
