java 时间戳转成 1970 年时,先检查原始字段约定是秒还是毫秒,再选择 instant.ofepochsecond 或 instant.ofepochmilli。1970 年也可能是合法值,不能仅凭年份或数字位数自动改单位。以下使用 jdk 17,各段分别保存为 main.java,编译后运行。

按接口单位创建 Instant,核对秒和毫秒对应同一时刻
秒与毫秒是距离同一纪元的不同单位,不是不同的时区。下面两个已知输入都表示 2024-01-01T00:00:00Z;把秒值交给毫秒方法则会得到不同时间。
import java.time.Instant;
public class Main {
public static void main(String[] args) {
long seconds = 1704067200L;
long millis = 1704067200000L;
Instant a = Instant.ofEpochSecond(seconds);
Instant b = Instant.ofEpochMilli(millis);
if (!a.equals(b)) throw new AssertionError();
if (!a.equals(Instant.parse("2024-01-01T00:00:00Z"))) throw new AssertionError();
Instant wrongUnit = Instant.ofEpochMilli(seconds);
if (wrongUnit.equals(a)) throw new AssertionError();
System.out.println(a);
System.out.println(wrongUnit);
}
}两次打印分别展示正确值和单位错误的值。这只是已知契约下的对照,不是根据数值大小猜测单位;原始接口或数据库字段说明才是判断依据。

立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
时间点确定后,再按指定时区显示
同一个 Instant 可以在不同时区显示为不同本地时间。北京时间比该例的 UTC 时间晚八小时,这与秒、毫秒换算是两步独立操作。
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
Instant point = Instant.ofEpochSecond(1704067200L);
LocalDateTime local = point.atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
if (!local.equals(LocalDateTime.of(2024, 1, 1, 8, 0))) throw new AssertionError();
if (!point.atZone(ZoneId.of("Asia/Shanghai")).toInstant().equals(point)) {
throw new AssertionError();
}
System.out.println(local);
}
}预期输出 2024-01-01T08:00。修改显示时区不能修复输入单位用错的问题;应先正确构造时间点,再选择展示时区。
转回原单位验证,保留合法的零时间戳
下面统一按“字段存秒”的契约读取。零值在该契约下是 Instant.EPOCH;如果业务把零当作未填写,需要在数据层另行定义,不能由日期转换器擅自判断。
import java.time.Instant;
public class Main {
static Instant parseSeconds(String text) {
return Instant.ofEpochSecond(Long.parseLong(text));
}
public static void main(String[] args) {
long value = 1704067200L;
Instant point = parseSeconds(Long.toString(value));
if (point.getEpochSecond() != value) throw new AssertionError();
if (point.toEpochMilli() != Math.multiplyExact(value, 1000L)) throw new AssertionError();
if (!parseSeconds("0").equals(Instant.EPOCH)) throw new AssertionError();
System.out.println(point.getEpochSecond());
System.out.println(point.toEpochMilli());
}
}真实输入还需要处理非数字、范围溢出等异常。含纳秒精度的时间点转成毫秒会损失更细精度,本节只验证整秒输入的回转结果。

















