59 lines
1.7 KiB
Java
59 lines
1.7 KiB
Java
|
|
package com.cdzy.common.utils;
|
|||
|
|
|
|||
|
|
import java.time.*;
|
|||
|
|
import java.time.format.DateTimeFormatter;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 数据类型转换工具类
|
|||
|
|
*
|
|||
|
|
* @author dingchao
|
|||
|
|
* @date 2025/3/24
|
|||
|
|
* @modified by:
|
|||
|
|
*/
|
|||
|
|
public class ConvertUtil {
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 时间戳转日期
|
|||
|
|
*
|
|||
|
|
* @param timestamp 时间戳
|
|||
|
|
* @return 日期
|
|||
|
|
*/
|
|||
|
|
public static LocalDateTime timestampToDate(long timestamp) {
|
|||
|
|
return LocalDateTime.ofEpochSecond(timestamp, 0, java.time.ZoneOffset.ofHours(8));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Instant转日期
|
|||
|
|
*
|
|||
|
|
* @param instant 时间戳
|
|||
|
|
* @return 日期
|
|||
|
|
*/
|
|||
|
|
public static LocalDateTime instantToDatetime(Instant instant) {
|
|||
|
|
return instant.atZone(ZoneId.of("+8")).toLocalDateTime();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 将 LocalDateTime 转换为 UTC。
|
|||
|
|
*
|
|||
|
|
* @param localDateTime 要转换的 LocalDateTime 对象
|
|||
|
|
* @return UTC时间字符串,格式为 "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
|
|||
|
|
*/
|
|||
|
|
public static String localDateTimeToUTC(LocalDateTime localDateTime) {
|
|||
|
|
ZonedDateTime localZoned = localDateTime.atZone(ZoneId.of("+8"));
|
|||
|
|
// 转换为 UTC 时区(自动减8小时)
|
|||
|
|
ZonedDateTime utcZoned = localZoned.withZoneSameInstant(ZoneOffset.UTC);
|
|||
|
|
// 定义格式化器,包含毫秒和时区标识'Z'
|
|||
|
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
|
|||
|
|
|
|||
|
|
// 格式化时间
|
|||
|
|
return utcZoned.format(formatter);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
//public static void main(String[] args) {
|
|||
|
|
// LocalDateTime localDateTime = LocalDateTime.now();
|
|||
|
|
// String utcTime = localDateTimeToUTC(localDateTime);
|
|||
|
|
// System.out.println("UTC 时间: " + utcTime);
|
|||
|
|
//}
|
|||
|
|
}
|