来源:宝马手游网 更新:2024-01-07 07:00:53
用手机看
在Java编程中,经常会遇到将时间戳转换为日期格式的需求。下面我将介绍一些常见的Java实现方法,帮助大家解决这个问题。
方法一:使用SimpleDateFormat类
SimpleDateFormat是Java中用于格式化和解析日期的类。通过指定日期格式,我们可以将时间戳转换为对应的日期字符串。以下是示例代码:
java import java.text.SimpleDateFormat; import java.util.Date; public class TimestampToDate { public static void main(String[] args){ long timestamp = 1620475200000L;//假设时间戳为2021年5月9日的毫秒数 Date date = new Date(timestamp); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = sdf.format(date); System.out.println(formattedDate);//输出:2021-05-09
方法二:使用Instant类
Java 8引入了新的日期和时间API,其中Instant类提供了将时间戳转换为日期的方法。以下是示例代码:
java import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class TimestampToDate { public static void main(String[] args){ long timestamp = 1620475200000L;//假设时间戳为2021年5月9日的毫秒数 Instant instant = Instant.ofEpochMilli(timestamp); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String formattedDate = localDateTime.format(formatter); System.out.println(formattedDate);//输出:2021-05-09
方法三:使用Calendar类
Calendar是Java中用于处理日期和时间的类。我们可以通过设置时间戳到Calendar对象中,然后获取对应的年、月、日等信息,进而得到日期字符串。
telegeram官方正版:https://bzmtv.com/danji/485.html