线程安全的时间工具类

 

目录

前言

LocalDateTime以及DateTimeFormatter

工具类

Instant 

语法


前言

之前总结过SimpleDateFormate是线程不安全的,主要是里面calendar是静态的,导致并发的时候会读取到之前的时间。

博客:https://blog.csdn.net/weixin_38336658/article/details/87470910

LocalDateTime以及DateTimeFormatter

这个是java8出的,线程安全的类。虽然说比Date使用会复杂一丢丢,但是还是ojk的。它还有LocalDate来操作日期,LocalTime来操作时间。

工具类

package com.example.demo.util;

import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author M
 */
public class TimeUtil {

    /**
     * 获取当前时间Date
     * @return Date
     */
    public static Date getNowDate(){
        return Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 格式化时间
     * @param date 时间
     * @param s 格式化字符串
     * @return String
     */
    public static String getDateFormat(Date date, String s){
        Assert.notNull(date,"时间为空");
        Assert.notNull(s,"格式化字符串为空");
        LocalDateTime localDateTime=date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        return localDateTime.format(DateTimeFormatter.ofPattern(s));
    }

    public static void main(String[] args) {
        System.out.println("当前时间"+getNowDate());
        System.out.println("格式化当前时间:"+getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
    }

}

包括两部分:一部分是获取当前时间,一般使用new Date()即可,后面是格式化时间,采用DateTimeFormate。

至于为啥最后转成Date类型,因为很多数据库里面时间类型就是Date

Instant 

在java8使用Instant去代替Date,不过最后还是得转Date,西西

语法

Instant.now()当前时间

Instant.now().atZone(ZoneId.systemDefault())指定时区时间

转Date Date.from(Instant)

发布了213 篇原创文章 · 获赞 31 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/weixin_38336658/article/details/100826213