[英]Days between to date of different timezone using Joda
我有一个格式为“2021-07-15T05:00:00.527+05:30”的输入日期字符串,我想要日期与当前时间的差异(当前时间为 UTC)。
DateTime inputDateTime = new DateTime(input, DateTimeZone.UTC);
DateTime now = new DateTime(DateTimeZone.UTC);
Days.daysBetween(now, inputDateTime).getDays();
如果我将输入日期转换为 UTC,则会产生错误的结果。 有没有办法从输入日期获取偏移量并将其添加到当前 UTC 日期,然后比较日期?
编辑:
抱歉把问题表述错了。 我试图找出给定的输入日期是今天还是前一天或明天是相对于 UTC 时区的偏移量。
在服务器中,时间为 2021-07-14T23:00:00.527Z 时,对于上述输入日期,应取为今天(即 0)。 如果在服务器时间是 2021-07-14T13:00:00.527Z,对于相同的输入数据,它应该是明天(即 1)。
编辑2:
我确实尝试将两者都转换为 localDate、 Days.daysBetween(now.toLocalDate(), inputDateTime.toLocalDate()).getDays()
但是当 UTC 时间在上一个日期 2021-07-14T23:00:00.527Z 和给定日期 2021-07-15T05:00:00.527+05:30,产生 1 但我希望它是 0 `
我正在尝试检查给定输入字符串的 isToday 或 isTomorrow。
我建议:
String input = "2021-07-19T05:00:00.527+05:30";
DateTime inputDateTime = new DateTime(input, DateTimeZone.UTC);
LocalDate inputDate = inputDateTime.toLocalDate();
LocalDate today = LocalDate.now(DateTimeZone.UTC);
boolean isToday = inputDate.equals(today);
LocalDate tomorrow = today.plusDays(1);
boolean isTomorrow = inputDate.equals(tomorrow);
System.out.format("Is today? + %b; is tomorrow? %b.%n", isToday, isTomorrow);
刚刚运行时的输出 - 7 月 18 日大约 18:32 UTC:
是今天? + 真; 是明天吗? 错误的。
我以输入字符串2021-07-19T05:00:00.527+05:30
为例。 它等于 2021-07-18T23:30:00.527Z (UTC)。 所以我比较今天和明天的日期是 2021-07-18。
来自 Joda-Time 主页的额外报价:
...请注意,从 Java SE 8 开始,要求用户迁移到
java.time
(JSR-310) - 替代该项目的 JDK 的核心部分。
(Joda-Time - 主页;粗体为原创)
对应的java.time代码类似。 只有从字符串到日期和时间的转换在文本上是不同的。 它明确表示正在进行偏移转换,我认为这是一个优势:
OffsetDateTime inputDateTime = OffsetDateTime.parse(input)
.withOffsetSameInstant(ZoneOffset.UTC);
LocalDate inputDate = inputDateTime.toLocalDate();
LocalDate today = LocalDate.now(ZoneOffset.UTC);
boolean isToday = inputDate.equals(today);
LocalDate tomorrow = today.plusDays(1);
boolean isTomorrow = inputDate.equals(tomorrow);
java.time
。java.time
到 Java 6 和 7 的 backport(ThreeTen for JSR-310)。我现在在我的代码中使用 java.time 做到了这一点。 我从输入日期获取偏移量,将其添加到当前 UTC 时间,然后获取两者的本地日期并进行比较。 不确定这是否涵盖夏令时等场景。
ZonedDateTime zonedScheduleDate = ZonedDateTime.parse(inputDate);
ZoneId zone = zonedScheduleDate.getZone();
ZonedDateTime instantAtUserTimezone = Instant.now().atZone(zone);
return (int) DAYS.between(instantAtUserTimezone.toLocalDate(), zonedScheduleDate.toLocalDate());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.