基于java8的时间操作工具类--解析时间、时间计算


import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.SignStyle;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.time.temporal.ChronoField.*;

/**
 * 基于java的8的进行时间操作的工具类
 * 包括格式化、解析、时间的加减等
 */
public class DateUtils8 {

    private  static  final  ZoneId zoneId = ZoneId.systemDefault();

    /**
     * 格式化为yyyy-MM-dd类型   如:2018-06-19
     */
    public  static final DateTimeFormatter DATE_STYLE ;


    /**
     * 格式化为:yyyy-MM-dd HH:mm:ss类型   如: 2018-06-19  12:12:23
     */
    public  static final DateTimeFormatter DATETIME_STYLE ;

    private static Pattern pattern = Pattern.compile("[0-9]+");


    static {
        DATE_STYLE = new DateTimeFormatterBuilder()
                .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
                .appendLiteral('-')
                .appendValue(MONTH_OF_YEAR, 2)
                .appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2)
                .toFormatter(Locale.getDefault());

        DATETIME_STYLE =  new DateTimeFormatterBuilder()
                .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
                .appendLiteral('-')
                .appendValue(MONTH_OF_YEAR, 2)
                .appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2)
                .appendLiteral(' ')
                .appendValue(HOUR_OF_DAY,2)
                .appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR,2)
                .appendLiteral(':')
                .appendValue(SECOND_OF_MINUTE,2)
                .toFormatter(Locale.getDefault());
    }

    /**
     * 将Date类型转换为 LocalDateTime
     * @date  要转换的date类
     * @return
     */
    public static LocalDateTime date2LocalDateTime(Date date){
        Instant instant = date.toInstant();
       return   instant.atZone(zoneId).toLocalDateTime();
    }

    /**
     * 将localDateTime转换为date
     * @param localDateTime
     * @return
     */
    public static Date  localDateTime2Date(LocalDateTime  localDateTime){
        ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);

        Instant instant = zonedDateTime.toInstant();
        return  Date.from(instant);
    }

    /**
     * 格式化日期
     * @param localDateTime
     * @return
     */
    public static String format(LocalDateTime localDateTime,DateTimeFormatter formatter){
       return localDateTime.format(formatter == null ? DATETIME_STYLE : formatter);
    }

    /**
     * 格式化日期
     * @param localDate
     * @return
     */
    public static String format(LocalDate localDate,DateTimeFormatter formatter){
        return localDate.format(formatter == null ? DATE_STYLE :formatter);
    }


    /**
     * 将字符串解析为LocalDateTime
     * @param text
     * @param formatter
     * @return
     */
    public  static LocalDateTime parseDateTime(CharSequence text,DateTimeFormatter formatter){
        return  LocalDateTime.parse(text, formatter == null ? DATETIME_STYLE :formatter);

    }


    /**
     * 将字符串解析为LocalDateTime  如:2018-08-09 12:13:31
     * @param text
     * @return
     */
    public  static LocalDateTime parseDateTime(CharSequence text){
        return  LocalDateTime.parse(text, DATETIME_STYLE );

    }

    /**
     *将字符串(2018-02-16)解析为  LocalDate
     * @param text
     * @return
     */
    public static LocalDate parseDate(CharSequence text,DateTimeFormatter formatter){

        return   LocalDate.parse(text, formatter == null?DATE_STYLE :formatter);

    }

    /**
     *将字符串(2018-02-16)解析为  LocalDate
     * @param text
     * @return
     */
    public static LocalDate parseDate(CharSequence text){
        return   LocalDate.parse(text, DATE_STYLE);

    }

    /**
     * 将字符串类型解析为时间
     * 至少需要保证有  年和月   如:2019-03-11,2019年03月2日 ,2019-3-11 12:13  、2019-3-11 12:13:13
     * 不能支持20190213这类字符串
     * @param text
     * @return
     */
    public static LocalDateTime parse(CharSequence text){

        Matcher matcher = pattern.matcher(text);
        //记录匹配数量
        int match = 0;
        int[] result = new int[6];
        result[2] = 1;
        while(matcher.find()){
            String group = matcher.group();
            result[match++] = Integer.parseInt(group);
        }

        if(match < 2) return  null;


        return  LocalDateTime.of(result[0],result[1],result[2] ,result[3],result[4],result[5]);
    }

    /**
     * 对时间进行加法操作
     * @param localDateTime
     * @param amountToAdd  要增加的值
     * @param unit    单位,可以选择年、月、周、天、日、时、分、秒等  java.time.temporal.ChronoUnit#DAYS
     * @return
     */
    public static LocalDateTime plus(LocalDateTime localDateTime,long amountToAdd, TemporalUnit unit ){
       return localDateTime.plus(amountToAdd,unit);
    }


    /**
     * 返回两个时间的 t2-t1的差值
     * @param t1
     * @param t2
     * @param unit  单位,可以选择年、月、周、天、日、时、分、秒等   java.time.temporal.ChronoUnit#DAYS
     * @return
     */
    public static long between(LocalDateTime t1,LocalDateTime t2,TemporalUnit unit){
       return unit.between(t1,t2);
    }


    /**
     * 获取指定时间或者今天第一秒及最后一秒的描述
     * 如今天是:20
     *  @param localDateTime
     * @return
     */
    public static String[] getLocalDateTimeDesc(LocalDateTime localDateTime){
        if(localDateTime == null ){
            localDateTime = LocalDateTime.now();
        }

        String[] res = new String[2];
        res[0] = localDateTime.withHour(0).withMinute(0).withSecond(0).format(DATETIME_STYLE);
        res[1] = localDateTime.withHour(23).withMinute(59).withSecond(59).format(DATETIME_STYLE);
        return res;
    }

    /**
     * 获取指定时间或者今天第一秒及最后一秒的描述
     * @param date
     * @return
     */
    public static String[] getDateTimeDesc(Date date){
        LocalDateTime localDateTime = null;
        if(date == null ){
            localDateTime = LocalDateTime.now();
        }else{
            localDateTime =   date2LocalDateTime(date);
        }
        return getLocalDateTimeDesc(localDateTime);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值