[英]Java - Convert a given DateTime in String to local timezone
我正在从数据库中读取时间戳作为字符串值,例如:
2020-04-30T09:59:00.272-05:00
. 现在我必须将其与本地时区(系统时区)中的当前时间戳进行比较
到目前为止我所尝试的:
ZonedDateTime result = ZonedDateTime.parse("2020-04-30T09:59:00.272-05:00"); System.out.println("Given: "+result); System.out.println("Given In Local: "+result.withZoneSameLocal(ZoneId.systemDefault()));
OutPut: Given: 2020-04-30T09:59:00.272-05:00 Given In Local: 2020-04-30T09:59:00.272-05:00[America/Chicago]
我想要的 output 是“2020-04-30T14:59:00.272”
您可以将给定的日期字符串解析为OffsetDateTime
,然后更改其偏移量并将其转换为LocalDateTime
如下
final String dateString = "2020-04-30T09:59:00.272-05:00";
final ZonedDateTime result = ZonedDateTime.parse(dateString);
System.out.println("Given : " + result);
final LocalDateTime localDateTime = OffsetDateTime.parse(dateString)
.atZoneSameInstant(ZoneId.of("Europe/Berlin"))
.toLocalDateTime();
System.out.println("Given In Local: " + localDateTime);```
印刷
Given : 2020-04-30T09:59:00.272-05:00
Given In Local: 2020-04-30T16:59:00.272
此外,您还可以将其解析为ZonedDateTime
然后更改时区,例如
final LocalDateTime result = ZonedDateTime.parse(dateString)
.withZoneSameInstant(ZoneId.of("Europe/Berlin"))
.toLocalDateTime();
我相信以下内容应该可以实现您的目的。
String dateTimeString = "2020-04-30T09:59:00.272-05:00";
OffsetDateTime databaseDateTime = OffsetDateTime.parse(dateTimeString );
OffsetDateTime currentDateTime = OffsetDateTime.now(ZoneId.systemDefault());
if (databaseDateTime.isAfter(currentDateTime)) {
System.out.println("" + databaseDateTime + " is after " + currentDateTime);
} else {
System.out.println("" + databaseDateTime + " is before or equal to " + currentDateTime);
}
Output 我刚才在我的时区(欧洲/哥本哈根)运行代码时:
2020-04-30T09:59:00.272-05:00 在 2020-04-26T21:48:36.331752+02:00 之后
由于数据库中的字符串包含 UTC 偏移量( -05:00
)并且没有时区(如 America/New_York),因此我发现解析为OffsetDateTime
更合适。 ZonedDateTime
将是矫枉过正。 对于本地时间,我将ZoneId.systemDefault()
传递给OffsetDateTime
的now
方法。 即使偏移量不同,使用isAfter()
比较两个OffsetDateTime
对象也能很好地工作,这一点已被考虑在内。 还有方法isBefore
和isEqual
用于比较。
退后一步,在大多数设置中,您不应该从数据库中获取日期和时间作为字符串。 Your JDBC 4.2 driver or your modern JPA implementation such as Hibernate 5 will be happy to fetch an OffsetDateTime
object from the database for you. 例如,请参见我的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.