java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java时间戳转换为日期

java时间戳转换为日期格式的多种方式

作者:康惠桀

本文介绍了五种将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时间戳转换为日期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文