我有像2020-05-25 08:03:24那样的字符串时间戳
我尝试使用split String (一个空格)作为分隔符,以获得两个String的"2020-05-25"和"08:03:24"。在此之后,我使用substring来获取时间,并添加了7以获得雅加达时间。
但例如,当它是17:01:00时,我的计算日期是错误的。
给出的日期是世界协调时。
我想把它转换成亚洲/雅加达时区,如何转换utc时间戳成为亚洲雅加达时间?
发布于 2020-05-25 08:33:07
如果使用的是Java 8或更高版本,则可以使用java.time。
该库提供了方便的可能性,可以将没有时区信息的日期时间(如您的示例String)转换为区域,并处理从一个区域到另一个区域的转换。
参见此示例:
public static void main(String[] args) {
// datetime string without a time zone or offset
String utcTimestamp = "2020-05-25 08:03:24";
// parse the datetime as it is to an object that only knows date and time (no zone)
LocalDateTime datetimeWithoutZone = LocalDateTime.parse(utcTimestamp,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// convert it to a zone-aware datetime object by adding a zone
ZonedDateTime utcZdt = datetimeWithoutZone.atZone(ZoneId.of("UTC"));
// print the datetime in utc once
System.out.println(utcZdt);
// then convert the zoned datetime to a different time zone
ZonedDateTime asiaJakartaZdt = utcZdt.withZoneSameInstant(ZoneId.of("Asia/Jakarta"));
// and print the result
System.out.println(asiaJakartaZdt);
}输出是
2020-05-25T08:03:24Z[UTC]
2020-05-25T15:03:24+07:00[Asia/Jakarta]https://stackoverflow.com/questions/61998441
复制相似问题