UTC LocalDateTime 根据时区转换

本示例演示如何将utc时间(格林威治实际标准时间)转换为北京时间(utc-东八区时间)。


有如下请求参数:
{
    "comeTime": "2020-11-15T00:01:45.000Z",

comeTime表示utc时间 2020年11月15日00点01分45秒。需要根据以上时间返回当前北京时间: 2020年11月15日08点01分45秒

@ApiOperation(value = "/getbjtime", notes = "根据utc时间返回utc-8北京时间")
public BaseOutputDto<String> getbjtime( 
        @ApiParam(value = "inputDto",name = "时间参数")
        @RequestBody InputDto inputDto)
{
     LocalDateTime comeTime = inputDto.getComeTime();
      return toUtcBeijing(comeTime);
}

public static LocalDateTime toUtcBeijing(LocalDateTime localDateTime){
    ZonedDateTime zonedtime = localDateTime.atZone(ZoneId.from(ZoneOffset.UTC));
    ZonedDateTime converted = zonedtime.withZoneSameInstant(ZoneOffset.ofHours(8));
    return converted.toLocalDateTime();
}

以下分享一个时区处理工具类

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public final class DateTimeUtil {
    private DateTimeUtil() {
        super();
    }

    public static void main(final String... args) {
        final LocalDateTime now = LocalDateTime.now();
        final LocalDateTime utc = DateTimeUtil.toUtc(now);

        System.out.println("Now: " + now);
        System.out.println("UTC: " + utc);
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
        final ZonedDateTime zonedtime = time.atZone(fromZone);
        final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
        return converted.toLocalDateTime();
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
        return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
    }

    public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
        return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
    }

    public static LocalDateTime toUtc(final LocalDateTime time) {
        return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
    }
}

 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值