Java时间处理函数:时间戳转换日期格式的10个方法
发布时间:2023-06-08 03:24:11
在Java中,时间戳指的是自1970年1月1日GMT(格林威治标准时间)起经过的毫秒数。将时间戳转换为日期格式是处理日期时间的常见任务。下面介绍10个方法,可以帮助您在Java中实现时间戳转换。
1. 使用Date类的构造函数直接将时间戳转换为日期对象
long timestamp = 1625361367000L; Date date = new Date(timestamp);
2. 使用DateFormat类的format()方法将日期对象格式化为字符串
long timestamp = 1625361367000L;
Date date = new Date(timestamp);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = df.format(date);
3. 使用Calendar类将时间戳转换为日期对象,并为其设置时间值
long timestamp = 1625361367000L; Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timestamp);
4. 使用SimpleDateFormat类将时间戳转换为字符串
long timestamp = 1625361367000L;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(new Date(timestamp));
5. 使用DateTimeFormatter类将时间戳转换为LocalDateTime对象
long timestamp = 1625361367000L; Instant instant = Instant.ofEpochMilli(timestamp); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
6. 使用DateTimeFormatter类将时间戳转换为字符串
long timestamp = 1625361367000L;
Instant instant = Instant.ofEpochMilli(timestamp);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
7. 使用ZonedDateTime类将时间戳转换为ZonedDateTime对象
long timestamp = 1625361367000L; ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
8. 使用ZonedDateTime类将时间戳转换为字符串
long timestamp = 1625361367000L;
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateString = zonedDateTime.format(formatter);
9. 使用java.sql.Timestamp类将时间戳转换为Timestamp对象
long timestamp = 1625361367000L; Timestamp ts = new Timestamp(timestamp);
10. 使用java.sql.Timestamp类将时间戳转换为字符串
long timestamp = 1625361367000L; Timestamp ts = new Timestamp(timestamp); String dateString = ts.toString();
总结:
本文介绍了Java中处理时间戳转换日期格式的10个方法,涵盖了常用的类和方法,希望能对您处理日期时间方面的任务有所帮助。在使用这些方法时,请注意时区的设置,以避免出现错误。
