在Java中有多种方式可以将时间戳转换为日期格式,下面详解4种常用的java时间戳转换日期格式。
SimpleDateFormat
SimpleDateFormat 是一个可以用来格式化日期的类,可以将日期对象转换为字符串。
如下所示:
long timestamp = System.currentTimeMillis(); Date date = new Date(timestamp); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = sdf.format(date);
DateTimeFormatter
DateTimeFormatter 是 Java 8 引入的日期和时间格式化工具,用于格式化和解析日期时间字符串。
如下所示:
long timestamp = System.currentTimeMillis(); // 使用Instant获取时间点 Instant instant = Instant.ofEpochMilli(timestamp); // 创建DateTimeFormatter对象,指定日期格式 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 格式化日期 String formattedDate = formatter.format(instant); System.out.println("Formatted Date (Java 8): " + formattedDate);
LocalDateTime
还可以使用LocalDateTime 和 DateTimeFormatter,来实现java时间戳转换日期格式。
如下所示:
long timestamp = System.currentTimeMillis(); LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDate = localDateTime.format(formatter); System.out.println("Custom Format with LocalDateTime (Java 8): " + formattedDate);
Apache Commons Lang
还可以使用第三方,Apache Commons Lang,来实现java时间戳转换日期格式。
如下所示:
long timestamp = System.currentTimeMillis(); // 使用Apache Commons Lang进行格式化 String formattedDate = DateFormatUtils.format(timestamp, "yyyy-MM-dd HH:mm:ss"); System.out.println("Formatted Date (Apache Commons Lang): " + formattedDate);
这些例子覆盖了不同的场景和日期格式,你可以根据实际需求选择适当的方式和格式。