本示例演示如何将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());
}
}