Java格式化日期 微秒
- Date、LocalDateTime格式化微秒值
- Date、LocalDateTime互转
本文主要讲述Java日期格式化及格式化日期到微秒
Date、LocalDateTime格式化微秒值
java代码TestTime.java如下
package com.dongao.test;import com.dongao.project.common.util.DateUtils;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;public class TestTime {public static void main(String[] args) {String str = "2022-07-04 23:57:29.696";Date date = stringToDate(str, "yyyy-MM-dd HH:mm:ss.SSS");System.out.println("date:["+date+"]");LocalDateTime datetime = stringToDateTime(str, "yyyy-MM-dd HH:mm:ss.SSS");System.out.println("datetime:["+datetime+"]");}public static Date stringToDate(String inStr, String dateFormat) {try {return getDateFormat(dateFormat).parse(inStr);} catch (ParseException e) {e.printStackTrace();}return null;}public static LocalDateTime stringToDateTime(String inStr, String dateFormat) {try {LocalDateTime localDateTime = LocalDateTime.parse(inStr, getDateTimeFormat(dateFormat));return localDateTime;} catch (Exception e) {e.printStackTrace();}return null;}public static SimpleDateFormat getDateFormat(String dateFormat) {return new SimpleDateFormat(dateFormat);}public static DateTimeFormatter getDateTimeFormat(String dateFormat) {return DateTimeFormatter.ofPattern(dateFormat);}
}
格式化结果执行

通过执行结果可以看到用SimpleDateFormat对含有微秒值的时间格式在字符串转Date时除了会出现精度丢失的情况,部分时间还会出现转换错误的情况,而用DateTimeFormatter对含有微妙值的时间格式字符串转LocalDateTime则一切正常。
但是一般业务不会用到时间格式的毫秒或者说微秒值,如果真的用到的话建议用LocalDateTime存储,Mysql需要用datetime(6)这样就可以保存微秒值的时间,如图

Date、LocalDateTime互转
在不考虑微秒或者毫秒时间精度丢失的情况下,Date、LocalDateTime可以相互转,main函数增加代码
Date toDate = toDate(datetime);System.out.println("toDate:["+toDate+"]");LocalDateTime toLocalDateTime = toLocalDateTime(date);System.out.println("toLocalDateTime:["+toLocalDateTime+"]");LocalDate toLocalDate = toLocalDate(date);System.out.println("toLocalDate:["+toLocalDate+"]");
整个类增加方法
public static Date toDate(LocalDateTime localDateTime) {Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();return Date.from(instant);}public static LocalDateTime toLocalDateTime(Date date) {Instant instant = date.toInstant();LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());return localDateTime;}public static LocalDate toLocalDate(Date date) {Instant instant = date.toInstant();LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());LocalDate localDate = localDateTime.toLocalDate();return localDate;}
转换之后结果如图

参考文章:https://developer.aliyun.com/article/982671



















