900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > UTC 包含 T Z 时间转换

UTC 包含 T Z 时间转换

时间:2023-07-15 10:26:28

相关推荐

UTC 包含 T Z 时间转换

import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;import java.time.format.DateTimeFormatter;public class UTCToBeijingTime {public static void main(String[] args) {// UTC时间字符串String utcTimeStr = "-05-02T12:34:56Z";// 创建UTC时间对象LocalDateTime utcTime = LocalDateTime.parse(utcTimeStr, DateTimeFormatter.ISO_DATE_TIME);// 将UTC时间转换为北京时间ZoneId utcZoneId = ZoneId.of("UTC");ZoneId beijingZoneId = ZoneId.of("Asia/Shanghai");ZonedDateTime utcDateTime = ZonedDateTime.of(utcTime, utcZoneId);ZonedDateTime beijingDateTime = utcDateTime.withZoneSameInstant(beijingZoneId);// 输出北京时间字符串String beijingTimeStr = beijingDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));System.out.println("北京时间:" + beijingTimeStr);}}北京时间:-05-02 20:34:56

其中,表示获取UTC时区对象,表示获取北京时区对象,表示将UTC时间转换为北京时间。 最后,使用格式化输出北京时间字符串。ZoneId.of(“UTC”)ZoneId.of(“Asia/Shanghai”)utcDateTime.withZoneSameInstant(beijingZoneId)DateTimeFormatter

java 字符串转 LocalDateTime

import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;public class StringToLocalDateTime {public static void main(String[] args) {String str = "-05-05T08:30:00";DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");LocalDateTime dateTime = LocalDateTime.parse(str, formatter);System.out.println(dateTime);}}

上述代码中,我们使用 DateTimeFormatter 定义了日期时间的格式,并且使用 parse 方法将字符串解析为 LocalDateTime 对象。 最终输出结果为 。 需要注意的是,DateTimeFormatter 中的格式要和字符串的格式完全一致,否则会抛出异常。-05-05T08:30

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。