欢迎访问宙启技术站
智能推送

java函数库提供的时间戳转日期时间格式函数

发布时间:2023-12-07 14:08:28

在Java函数库中,提供了多种方式将时间戳转换为日期时间格式。下面我会介绍其中的几种常用方法:

1. 使用Date类:Date类是Java中表示日期时间的核心类之一。可以使用它的构造函数将时间戳转换为Date对象,然后通过SimpleDateFormat类对Date对象进行格式化。

示例代码:

long timestamp = 1612345678901L; // 时间戳(以毫秒为单位)
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // 输出 2021-02-03 16:01:18

2. 使用LocalDateTime类:Java 8及以上版本中新增了java.time包,其中的LocalDateTime类提供了更加灵活和易用的日期时间操作方法。可以使用其静态方法ofEpochMilli将时间戳转换为LocalDateTime对象,然后通过DateTimeFormatter类对LocalDateTime对象进行格式化。

示例代码:

long timestamp = 1612345678901L; // 时间戳(以毫秒为单位)
Instant instant = Instant.ofEpochMilli(timestamp);
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime); // 输出 2021-02-03 16:01:18

3. 使用Calendar类:Calendar类是Java提供的日历操作类,也可以用于时间戳的转换。可以使用其setTimeInMillis方法将时间戳设置进Calendar对象,然后通过DateFormat类对Calendar对象进行格式化。

示例代码:

long timestamp = 1612345678901L; // 时间戳(以毫秒为单位)
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = dateFormat.format(calendar.getTime());
System.out.println(formattedDateTime); // 输出 2021-02-03 16:01:18

以上就是几种常用的时间戳转日期时间格式的方法,可以根据实际需求选择适合的方法进行使用。无论是使用Date类还是LocalDateTime类或者Calendar类,都可以达到相同的转换效果。