
java时间戳转换为日期格式
java时间戳转换为日期格式
·
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时间戳转换为日期格式的实现方法,它们都是可行的,并且可以根据具体需求选择适合的方法。
更多推荐
所有评论(0)