我有一个格式 (HH: mm: ss) 的 UTC 字符串,我需要将字符串值转换为相同格式的设备时间 (HH: mm: ss) 并且如果可用还添加日间节约时间我曾尝试转换通过此代码将 UTC 字符串转换为设备时间,但由于(节省时间),我延迟了 1 小时。
String utcTimeString = "12:15:00"
SimpleDateFormat formatter = new SimpleDateFormat("HH: mm: ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(utcTimeString);
SimpleDateFormat dateFormatter = new SimpleDateFormat("HH: mm: ss");
dateFormatter.setTimeZone(TimeZone.getDefault());
utcDateString = dateFormatter.format(value);
我的时区是 GMT-4
预期输出:08:15:00;给定输出:07:15:00;
您可以使用java.time
现代日期时间 API,并将时间解析String
为某个时刻,即Instant
.
然后使用ZonedDateTime
对象来应用某个时区,这可能以不同的方式完成,我在这里向您展示其中之一:
public static void main(String[] args) {
// the source is just a time, but to correctly convert it, you need a date
String utcTime = "12:15:00";
// take today's date
LocalDate today = LocalDate.now();
// create a parseable date time String
String parseableDateTime = today.format(DateTimeFormatter.ISO_DATE) + "T" + utcTime + "Z";
// then create an Instant parsing the date time String
Instant instant = Instant.parse(parseableDateTime);
// get the ZoneId of UTC in order to have the time in UTC
ZoneId utc = ZoneId.of("UTC");
// do the same with your ZoneOffset of -4 Hours
ZoneId gmtMinusFour = ZoneId.ofOffset("GMT", ZoneOffset.ofHours(-4));
// create a UTC ZonedDateTime of the instant and the UTC ZoneID
ZonedDateTime utcZdt = ZonedDateTime.ofInstant(instant, utc);
// then use that ZonedDateTime to convert it to a time with your ZoneId
ZonedDateTime gmtMinusFourZdt = utcZdt.withZoneSameInstant(gmtMinusFour);
// finally print both ZonedDateTimes in order to compare them
System.out.println("UTC time is:\t\t"
+ utcZdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println("GMT-4 time is:\t\t"
+ gmtMinusFourZdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// then just get the time part of the converted ZonedDateTime
LocalTime localTime = gmtMinusFourZdt.toLocalTime();
// and print it
System.out.println("Converted time is:\t"
+ localTime.format(DateTimeFormatter.ISO_TIME));
}
输出:
UTC time is: 2019-09-24T12:15:00Z[UTC]
GMT-4 time is: 2019-09-24T08:15:00-04:00[GMT-04:00]
Converted time is: 08:15:00
可能有更好的解决方案,但无论如何我希望这会有所帮助......
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句