Java时间类型总结

发布时间 2023-10-08 16:12:59作者: 7Aom1

1.为什么需要新的时间类型

1.8之后为什么需要LocalDate、LocalTime、LocalDateTime

因为之前原生的Date如果不格式化,那么打印出来的日期可视化差,例如下面

Tue Sep 10 09:34:04 CST 2019

你会说使用SimpleDateFormat()方法,如下所示。

public class FormatDateTime {
    public static void main(String[] args) {
        SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm");
        SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等价于now.toLocaleString()
        SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");
        SimpleDateFormat myFmt4=new SimpleDateFormat("一年中的第 D 天 一年中第w个星期 一月中第W个星期 在一天中k时 z时区");
        Date now=new Date();
        System.out.println(myFmt.format(now));
        System.out.println(myFmt1.format(now));
        System.out.println(myFmt2.format(now));
        System.out.println(myFmt3.format(now));
        System.out.println(myFmt4.format(now));
        System.out.println(now.toGMTString());
        System.out.println(now.toLocaleString());
        System.out.println(now.toString());z
        
        //parse方法可以把String型的字符串转换成特定格式的date类型,使用parse时字符串长度要和定义的SimpleDateFormat对象长度一致
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String s = sdf.parse(Info.getTopDate()).toString();
		//format方法可以把Date型的字符串转换成特定格式的String类型,如果Date类型和定义的SimpleDateFormat长度不一致会自动在后面补充0
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowDate = sdf.format(new Date());
    }     
}

但是也不推荐使用,SimpleDateFormat()方法,会导致线程不安全。

    // Called from Format after creating a FieldDelegate
    private StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldDelegate delegate) {
        // Convert input date to time field list
        calendar.setTime(date);
        boolean useDateFormatSymbols = useDateFormatSymbols();
        for (int i = 0; i < compiledPattern.length; ) {
            int tag = compiledPattern[i] >>> 8;
            int count = compiledPattern[i++] & 0xff;
            if (count == 255) {
                count = compiledPattern[i++] << 16;
                count |= compiledPattern[i++];
            }

            switch (tag) {
            case TAG_QUOTE_ASCII_CHAR:
                toAppendTo.append((char)count);
                break;

            case TAG_QUOTE_CHARS:
                toAppendTo.append(compiledPattern, i, count);
                i += count;
                break;

            default:
                subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
                break;
            }
        }
        return toAppendTo;
    }

这里有个calendar对象,calendar是共享变量,并且这个共享变量没有做线程安全控制。当多个线程同时使用相同的SimpleDateFormat对象,如用static修饰的SimpleDateFormat调用format方法时,多个线程会同时调用calendar.setTime方法,可能一个线程刚设置好time值另外的一个线程马上把设置的time值给修改了导致返回的格式化时间可能是错误的。在多并发情况下使用SimpleDateFormat需格外注意SimpleDateFormat除了format是线程不安全以外,parse方法也是线程不安全的。parse方法实际调用alb.establish(calendar).getTime()方法来解析,alb.establish(calendar)方法里主要完成了

  • 1、 重置日期对象cal的属性值
  • 2、使用calb中中属性设置cal
  • 3、返回设置好的cal对象

那么如何确保使用SimpleDateFormat的时候线程安全呢?

  • 避免线程之间共享一个simpleDateFormat对象,每个线程都创建一个simpleDateFormat------》导致创建的开销大。
  • 对使用formatparse方法的地方进行加锁 => 线程阻塞性能差
  • 对使用formatparse方法的地方进行加锁 => 线程阻塞性能差
  • 使用ThreadLocal保证每个线程最多只创建一次SimpleDateFormat对象 => 较好的方法
  • 使用FastDateFormat

2.LocalDate,LocalTime,LocalDateTime,instant

三者有什么区别呢?

LocalDate:只会获取年月日

//创建LocalDate
//获取当前年月日
LocalDate localDate = LocalDate.now();
//构造指定的年月日
LocalDate localDate1 = LocalDate.of(2019, 9, 10);
获取年、月、日、星期几
int year = localDate.getYear();
//ChronoField是java8提供的一个枚举类,里面定义了很多表示日历的字段,提供基于字段的访问来操纵日期,时间或日期时间, 通过实现TemporalField来扩展标准字段集。
int year1 = localDate.get(ChronoField.YEAR);
Month month = localDate.getMonth();
int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);
int day = localDate.getDayOfMonth();
int day1 = localDate.get(ChronoField.DAY_OF_MONTH);
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);

LocalTime:只会获取几点几分几秒

//创建LocalTime
LocalTime localTime = LocalTime.of(13, 51, 10);
LocalTime localTime1 = LocalTime.now();
//获取时分秒
//获取小时
int hour = localTime.getHour();
int hour1 = localTime.get(ChronoField.HOUR_OF_DAY);
//获取分
int minute = localTime.getMinute();
int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR);
//获取秒
int second = localTime.getSecond();
int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);

LocalDateTime:获取年月日时分秒,等于LocalDate+LocalTime

//取年月日时分秒,等于LocalDate+LocalTime

//创建LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56);
LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
LocalDateTime localDateTime3 = localDate.atTime(localTime);
LocalDateTime localDateTime4 = localTime.atDate(localDate);
//获取LocalDate
LocalDate localDate2 = localDateTime.toLocalDate();
//获取LocalTime
LocalTime localTime2 = localDateTime.toLocalTime();

instant

//获取秒数
//创建Instant对象
Instant instant = Instant.now();
//获取秒数
long currentSecond = instant.getEpochSecond();
//获取毫秒数
long currentMilli = instant.toEpochMilli();
//个人觉得如果只是为了获取秒数或者毫秒数,使用System.currentTimeMillis()来得更为方便

格式化时间

LocalDate localDate = LocalDate.of(2019, 9, 10);
String s1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
String s2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
//自定义格式化
DateTimeFormatter dateTimeFormatter =   DateTimeFormatter.ofPattern("dd/MM/yyyy");
String s3 = localDate.format(dateTimeFormatter);

DateTimeFormatter默认提供了多种格式化方式,如果默认提供的不能满足要求,可以通过DateTimeFormatterofPattern方法创建自定义格式化方式

2.1解析时间

LocalDate localDate1 = LocalDate.parse("20190910", DateTimeFormatter.BASIC_ISO_DATE);
LocalDate localDate2 = LocalDate.parse("2019-09-10", DateTimeFormatter.ISO_LOCAL_DATE);

3.Springboot中应用LocalDateTime

将LocalDateTime字段以时间戳的方式返回给前端 添加日期转化类

public class LocalDateTimeConverter extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeNumber(value.toInstant(ZoneOffset.of("+8")).toEpochMilli());}}

并在LocalDateTime字段上添加@JsonSerialize(using = LocalDateTimeConverter.class)

//注解,如下:
@JsonSerialize(using = LocalDateTimeConverter.class)
protected LocalDateTime gmtModified;

将LocalDateTime字段以指定格式化日期的方式返回给前端 在
LocalDateTime字段上添加@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")

//注解即可,如下:
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
protected LocalDateTime gmtModified;

对前端传入的日期进行格式化 在LocalDateTime字段上添加@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

//注解即可,如下:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
protected LocalDateTime gmtModified;

参考:

【死磕 Java NIO】— 阻塞、非阻塞、同步、异步 - 死磕 Java (skjava.com)