java时间戳转换为日期格式的多种方式
更新时间:2025年01月19日 15:00:30 作者:康惠桀
本文介绍了五种将Java时间戳转换为日期格式的方法,包括使用Date类、LocalDateTime类、Instant类、DateUtils类以及自定义时区,每种方法都有其适用场景,可以根据具体需求选择合适的方法,感兴趣的朋友跟随小编一起看看吧
java时间戳转换为日期格式
以下是几种将Java时间戳转换为日期格式的实现方法:
方法一:使用Java的Date类和SimpleDateFormat类
long timestamp = 1617142526000L; // 时间戳值
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);方法二:使用Java 8的LocalDateTime类和DateTimeFormatter类
long timestamp = 1617142526000L; // 时间戳值
Instant instant = Instant.ofEpochMilli(timestamp);
LocalDateTime date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = date.format(formatter);
System.out.println(formattedDate);方法三:使用Java 8的java.time包中的Instant类和DateTimeFormatter类
long timestamp = 1617142526000L; // 时间戳值
Instant instant = Instant.ofEpochMilli(timestamp);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
String formattedDate = zonedDateTime.format(formatter);
System.out.println(formattedDate);方法四:使用Java 8的java.time包中的Instant类和DateTimeFormatter类,使用自定义时区
long timestamp = 1617142526000L; // 时间戳值
Instant instant = Instant.ofEpochMilli(timestamp);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));
String formattedDate = zonedDateTime.format(formatter);
System.out.println(formattedDate);方法五:使用Apache Commons Lang库的DateUtils类
import org.apache.commons.lang3.time.DateFormatUtils; import java.util.Date; long timestamp = 1617142526000L; // 时间戳值 Date date = new Date(timestamp); String formattedDate = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"); System.out.println(formattedDate);
以上是几种将Java时间戳转换为日期格式的实现方法,它们都是可行的,并且可以根据具体需求选择适合的方法。
到此这篇关于java时间戳转换为日期格式的文章就介绍到这了,更多相关java时间戳转换为日期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringMVC整合SpringSession 实现sessiong
这篇文章主要介绍了SpringMVC整合SpringSession 实现session的实例代码,本文通过实例相结合的形式给大家介绍的非常详细,需要的朋友参考下吧2018-04-04
java使用xstream实现xml文件和对象之间的相互转换
xml是一个用途比较广泛的文件类型,在java里也自带解析xml的包,但是本文使用的是xstream来实现xml和对象之间的相互转换,xstream是一个第三方开源框架,使用起来比较方便,对java xml和对象转换相关知识感兴趣的朋友一起看看吧2023-09-09
关于HttpClient 引发的线程太多导致FullGc的问题
这篇文章主要介绍了关于HttpClient 引发的线程太多导致FullGc的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-01-01


最新评论