时间戳在Java后端开发中非常重要,用于记录时间、计算时间间隔、排序时间等操作。下面我将详细介绍Java中时间戳的使用方法。
1. 时间戳基本概念
时间戳(Timestamp)通常指从1970年1月1日00:00:00 GMT开始到现在的总秒数或毫秒数。
2. 获取时间戳的方法
2.1 System.currentTimeMillis()
long timestamp = System.currentTimeMillis();
System.out.println("当前时间戳(毫秒): " + timestamp);
2.2 java.util.Date
Date date = new Date();
long timestamp = date.getTime();
System.out.println("Date获取的时间戳: " + timestamp);
2.3 java.time包(Java 8+推荐)
// 毫秒时间戳
long millisTimestamp = Instant.now().toEpochMilli();
System.out.println("Instant毫秒时间戳: " + millisTimestamp);
// 秒时间戳
long secondsTimestamp = Instant.now().getEpochSecond();
System.out.println("Instant秒时间戳: " + secondsTimestamp);
3. 时间戳与日期转换
3.1 时间戳转Date
long timestamp = System.currentTimeMillis();
Date date = new Date(timestamp);
System.out.println("时间戳转Date: " + date);
3.2 时间戳转LocalDateTime(Java 8+)
long timestamp = System.currentTimeMillis();
LocalDateTime dateTime = Instant.ofEpochMilli(timestamp)
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
System.out.println("时间戳转LocalDateTime: " + dateTime);
3.3 日期转时间戳
LocalDateTime dateTime = LocalDateTime.now();
long timestamp = dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println("LocalDateTime转时间戳: " + timestamp);
4. 时间戳格式化
4.1 使用SimpleDateFormat
long timestamp = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(new Date(timestamp));
System.out.println("格式化时间: " + formattedDate);
4.2 使用DateTimeFormatter(Java 8+)
long timestamp = System.currentTimeMillis();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = Instant.ofEpochMilli(timestamp)
.atZone(ZoneId.systemDefault())
.format(formatter);
System.out.println("DateTimeFormatter格式化: " + formattedDate);
5. 时间戳计算
5.1 加减时间
long now = System.currentTimeMillis();
long oneHourLater = now + 3600 * 1000; // 加1小时(3600秒*1000毫秒)
System.out.println("一小时后的时间戳: " + oneHourLater);
5.2 计算时间差
long start = System.currentTimeMillis();
// 模拟一些操作
Thread.sleep(1500);
long end = System.currentTimeMillis();
long duration = end - start;
System.out.println("操作耗时(毫秒): " + duration);
6. 数据库中的时间戳
6.1 MySQL时间戳
// 获取数据库时间戳
Timestamp dbTimestamp = resultSet.getTimestamp("create_time");
// 设置PreparedStatement参数
preparedStatement.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
6.2 与LocalDateTime转换
// Timestamp转LocalDateTime
Timestamp timestamp = resultSet.getTimestamp("create_time");
LocalDateTime dateTime = timestamp.toLocalDateTime();
// LocalDateTime转Timestamp
Timestamp ts = Timestamp.valueOf(LocalDateTime.now());
7. 注意事项
-
时区问题:时间戳是UTC时间,转换为本地时间时需要考虑时区
-
精度问题:System.currentTimeMillis()是毫秒级,Instant.now()可以获取纳秒级精度
-
线程安全:SimpleDateFormat不是线程安全的,建议每个线程单独创建或使用ThreadLocal
-
Java 8+推荐:在新项目中推荐使用java.time包中的类,它们是不可变的且线程安全
8. 最佳实践
-
在系统内部使用时间戳进行时间计算和存储
-
仅在需要显示或与用户交互时将时间戳转换为可读格式
-
日志记录时可以使用时间戳便于后续分析
-
分布式系统中使用统一的时间源(如NTP服务器)确保时间一致