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 中获取时区的当前日期和时间?
基础教程推荐
- Maven:无效的目标版本:10 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 将 Windows 证书导入 Java 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
