1. 方法定义
public void setTime(long time)
- 所属类:
java.util.Date
- 参数:
time
- 自 1970年1月1日 00:00:00 GMT(Unix 纪元)以来的毫秒数。 - 返回值:无(
void
) - 异常:无(不抛出异常)
2. 功能说明
setTime()
方法用于将 Date
对象的时间设置为指定的毫秒值。该毫秒值是相对于 Unix 纪元(1970年1月1日 00:00:00 GMT) 的偏移量。
此方法允许你:
- 修改一个已存在的
Date
对象的时间,而无需创建新对象。 - 将一个
Date
实例重置为另一个时间点。
3. 示例代码
基本用法
import java.util.Date;
public class DateSetTimeExample {
public static void main(String[] args) {
Date date = new Date();
System.out.println("原始时间: " + date);
// 设置为 2025年1月1日 00:00:00 GMT
long newTime = 1735689600000L; // 可通过在线时间戳工具获取
date.setTime(newTime);
System.out.println("修改后时间: " + date);
}
}
动态设置时间
Date date = new Date();
long currentTimeMillis = System.currentTimeMillis();
date.setTime(currentTimeMillis + 86400000); // 设置为明天同一时间
System.out.println("明天此时: " + date);
复制时间值
Date sourceDate = new Date();
Date targetDate = new Date();
// 复制 sourceDate 的时间到 targetDate
targetDate.setTime(sourceDate.getTime());
System.out.println("复制后时间一致: " + targetDate.equals(sourceDate)); // true
4. 使用技巧
✅ 技巧 1:避免频繁创建新对象
// 推荐:复用 Date 对象
Date reusableDate = new Date();
for (int i = 0; i < 1000; i++) {
reusableDate.setTime(System.currentTimeMillis() + i * 1000);
// 使用 reusableDate
}
✅ 技巧 2:结合 Calendar 使用(旧代码兼容)
Calendar cal = Calendar.getInstance();
cal.set(2025, Calendar.JANUARY, 1);
Date date = new Date();
date.setTime(cal.getTimeInMillis());
✅ 技巧 3:精确时间控制
// 设置精确到毫秒的时间
long preciseTime = 1735689600123L; // 包含毫秒部分
date.setTime(preciseTime);
5. 常见错误
❌ 错误 1:传入错误的时间戳
// 错误:传入的是秒级时间戳(常见于 JSON 数据)
long seconds = 1735689600; // 这是秒
date.setTime(seconds); // 时间会是 1970 年代!
// 正确做法:
date.setTime(seconds * 1000); // 转换为毫秒
❌ 错误 2:忽略时区影响
// 注意:setTime() 使用的是 GMT 时间
// 显示时会根据本地时区转换,可能导致误解
❌ 错误 3:在多线程环境中共享可变 Date
// 危险:多个线程修改同一个 Date 对象
Date sharedDate = new Date();
// 多个线程调用 sharedDate.setTime(...) 可能导致数据不一致
6. 注意事项
线程安全:
Date
对象本身不是线程安全的。如果多个线程共享同一个Date
实例并调用setTime()
,必须进行同步控制。时区处理:
setTime()
使用的是 GMT 时间,但toString()
显示的是本地时区时间,注意区分。精度限制:
Date
的精度为毫秒,无法表示纳秒级时间(应使用java.time.Instant
)。已过时建议:虽然
Date
仍广泛使用,但官方推荐使用java.time
包中的新时间 API(Java 8+)。负值处理:可以传入负数(表示 1970 年之前的时间),但需确保逻辑正确。
7. 最佳实践与性能优化
✅ 最佳实践 1:优先使用 java.time
API(推荐)
// Java 8+ 推荐方式
import java.time.Instant;
Instant now = Instant.now();
Instant modified = now.plusSeconds(3600); // 一小时后
✅ 最佳实践 2:封装 Date 操作
public class DateUtils {
public static Date fromTimestamp(long timestamp) {
Date date = new Date();
date.setTime(timestamp);
return date;
}
public static void setToNow(Date date) {
date.setTime(System.currentTimeMillis());
}
}
✅ 最佳实践 3:避免在循环中创建大量 Date 对象
// 优化前
for (int i = 0; i < 10000; i++) {
Date d = new Date(System.currentTimeMillis() + i);
}
// 优化后
Date reusable = new Date();
for (int i = 0; i < 10000; i++) {
reusable.setTime(System.currentTimeMillis() + i);
}
✅ 性能提示
setTime()
本身非常快(只是赋值操作)。- 性能瓶颈通常出现在
toString()
、格式化或频繁创建对象。 - 在高并发场景下,考虑使用
ThreadLocal<Date>
避免同步开销。