Java8的DateTimeFormatter与SimpleDateFormat的区别详解
两者最大的区别是,Java8的DateTimeFormatter是线程安全的,而SimpleDateFormat并不是线程安全。
package com.main;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class Main {
public static void main(String args[]){
//解析日期
String dateStr= "2016年10月25日";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
LocalDate date= LocalDate.parse(dateStr, formatter);
//日期转换为字符串
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm a");
String nowStr = now .format(format);
System.out.println(nowStr);
//ThreadLocal来限制SimpleDateFormat
System.out.println(format(new Date()));
}
//要在高并发环境下能有比较好的体验,可以使用ThreadLocal来限制SimpleDateFormat只能在线程内共享,这样就避免了多线程导致的线程安全问题。
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static String format(Date date) {
return threadLocal.get().format(date);
}
}
Java8 (LocalDateTime) 时间转换
注意:LocalDateTime是带时分秒的
1.将LocalDateTime转为自定义的时间格式的字符串
public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return localDateTime.format(formatter);
}
2.将long类型的timestamp转为LocalDateTime
public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
3.将LocalDateTime转为long类型的timestamp
public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return instant.toEpochMilli();
}
4.将某时间字符串转为自定义时间格式的LocalDateTime
public static LocalDateTime parseStringToDateTime(String time, String format) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(time, df);
}
到此这篇关于Java8的DateTimeFormatter与SimpleDateFormat的区别详解的文章就介绍到这了,更多相关Java8 DateTimeFormatter与SimpleDateFormat内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
java多线程开发之通过对战游戏学习CyclicBarrier
这篇文章给大家分享了关于java多线程开发中通过对战游戏学习CyclicBarrier的相关知识点内容,有兴趣的朋友们学习参考下。2018-08-08
解决Mybatis-Plus更新方法不更新NULL字段的问题
这篇文章主要介绍了解决Mybatis-Plus更新方法不更新NULL字段的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-12-12
解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题
文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析了可能的原因,并提供了解决步骤2025-01-01
Spring Cloud Gateway自定义异常处理Exception Handler的方法小结
这篇文章主要介绍了Spring Cloud Gateway自定义异常处理Exception Handler的方法,本文通过两种方法结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-08-08


最新评论