long currentTime = System.currentTimeMillis(); System.out.println("当前时间戳:" + currentTime);
LocalDateTime now = LocalDateTime.now(); System.out.println("当前本地时间:" + now);
// 获取时间的各个部分 int year = now.getYear(); Month month = now.getMonth(); int day = month.getValue(); int hour = now.getHour(); int minute = now.getMinute();
System.out.println(year + "年" + day + "月" + now.getDayOfMonth() + "日 " +
hour + "时" + minute + "分");
Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formatted = sdf.format(now); System.out.println("格式化时间:" + formatted);
// 更多格式示例 SimpleDateFormat dateOnly = new SimpleDateFormat("yyyy年MM月dd日"); SimpleDateFormat timeOnly = new SimpleDateFormat("HH时mm分ss秒");
System.out.println("仅日期:" + dateOnly.format(now)); System.out.println("仅时间:" + timeOnly.format(now));
// 获取时间戳的多种方式 long timestamp1 = System.currentTimeMillis(); long timestamp2 = Instant.now().toEpochMilli(); long timestamp3 = new Date().getTime();
System.out.println("当前时间戳:" + timestamp1); System.out.println("Instant时间戳:" + timestamp2); System.out.println("Date时间戳:" + timestamp3);
// 时间戳转换为可读时间 Instant instant = Instant.ofEpochMilli(timestamp1); LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); System.out.println("时间戳对应时间:" + dateTime);
// 性能测试示例 public class TimePerformanceTest {
public static void main(String[] args) {
int iterations = 1_000_000;
// System.currentTimeMillis()
long start1 = System.nanoTime();
for (int i = 0; i < iterations; i++) {
long time = System.currentTimeMillis();
}
long duration1 = System.nanoTime() - start1;
// Instant.now()
long start2 = System.nanoTime();
for (int i = 0; i < iterations; i++) {
Instant instant = Instant.now();
}
long duration2 = System.nanoTime() - start2;
// new Date()
long start3 = System.nanoTime();
for (int i = 0; i < iterations; i++) {
Date date = new Date();
}
long duration3 = System.nanoTime() - start3;
System.out.println("System.currentTimeMillis(): " + duration1 / 1_000_000 + " ms");
System.out.println("Instant.now(): " + duration2 / 1_000_000 + " ms");
System.out.println("new Date(): " + duration3 / 1_000_000 + " ms");
}
}
// 错误示例 - 非线程安全 public class UnsafeTimeFormatter {
private static final SimpleDateFormat formatter =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public String formatDate(Date date) {
return formatter.format(date); // 多线程下可能出错
}
}
// 正确做法 - 使用ThreadLocal public class SafeTimeFormatter {
private static final ThreadLocal<SimpleDateFormat> formatter =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public String formatDate(Date date) {
return formatter.get().format(date);
}
}
// 更好的选择 - 使用DateTimeFormatter public class ModernTimeFormatter {
private static final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public String formatDate(LocalDateTime dateTime) {
return dateTime.format(formatter); // 线程安全
}
}