package cn.org.hentai.jtt1078.util;
|
import java.nio.ByteBuffer;
|
import java.time.Instant;
|
import java.time.ZoneOffset;
|
import java.time.ZonedDateTime;
|
import java.time.format.DateTimeFormatter;
|
|
public class TimeUtils {
|
|
/**
|
* 将8字节时间戳字节数组(大端序)转成格式化时间字符串(UTC时区)
|
* @param bytes 8字节数组,表示自Unix纪元以来的毫秒数
|
* @return 格式化时间字符串,例如:"2025-07-30 12:34:56"
|
*/
|
public static String bytes8ToTimeString(byte[] bytes) {
|
if (bytes == null || bytes.length != 8) {
|
throw new IllegalArgumentException("字节数组必须为8字节长度");
|
}
|
// 默认大端字节序读取long
|
long timestampMillis = ByteBuffer.wrap(bytes).getLong();
|
|
Instant instant = Instant.ofEpochMilli(timestampMillis);
|
ZonedDateTime utcTime = instant.atZone(ZoneOffset.UTC);
|
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneOffset.UTC);
|
return formatter.format(utcTime);
|
}
|
|
public static long bytes8ToLong(byte[] bytes) {
|
if (bytes == null || bytes.length != 8) throw new IllegalArgumentException("Invalid byte array");
|
return ((long)(bytes[0] & 0xFF) << 56) |
|
((long)(bytes[1] & 0xFF) << 48) |
|
((long)(bytes[2] & 0xFF) << 40) |
|
((long)(bytes[3] & 0xFF) << 32) |
|
((long)(bytes[4] & 0xFF) << 24) |
|
((long)(bytes[5] & 0xFF) << 16) |
|
((long)(bytes[6] & 0xFF) << 8) |
|
((long)(bytes[7] & 0xFF));
|
}
|
|
public static void main(String[] args) {
|
// 示例8字节时间戳
|
byte[] tsBytes = new byte[]{0, 0, 1, 122, 68, 95, -54, 0}; // 例子
|
System.out.println(bytes8ToTimeString(tsBytes));
|
}
|
}
|