zoukankan      html  css  js  c++  java
  • 日期时间工具类DateTimeUtil(基于Java8的LocalDateTime)

    1.格式化常量字符串

    public class TimeFormatter {
    
        //构造方法私有化:该类本身地方除外的其他地方无法实例化该类对象
        private TimeFormatter() {
        }
    
        public static final String DATETIME_FORMATTER = "yyyy-MM-dd HH:mm:ss";
    
        public static final String DATE_FORMATTER = "yyyy-MM-dd";
    
        public static final String TIME_FORMATTER = "HH:mm:ss";
    
        public static final String DATETIME_T_FORMATTER = "yyyy-MM-dd'T'HH:mm:ss";
    
    }

    2.DateTimeUtil日期时间工具类

    public class DateTimeUtil {
    
        /**
         * 获取当前时间时间戳(long)
         * @return
         */
        public static long currentTimeMillis() {
            return System.currentTimeMillis();
        }
    
        /**
         * 获取当前日期(yyyy-MM-dd)
         * @return
         */
        public static LocalDate currentLocalDate() {
            return LocalDate.now();
        }
    
        /**
         * 获取当前时间(HH:mm:ss.SSS)
         * @return
         */
        public static LocalTime currentLocalTime() {
            return LocalTime.now();
        }
    
        /**
         * 获取当前日期时间(yyyy-MM-dd'T'HH:mm:ss.SSS)
         * @return
         */
        public static LocalDateTime currentLocalDateTime() {
            return LocalDateTime.now();
        }
    
        /**
         * 获取当前日期字符串(yyyy-MM-dd)
         * @return
         */
        public static String getCurrentDateStr() {
            return DateTimeFormatter.ofPattern(TimeFormatter.DATE_FORMATTER).format(currentLocalDateTime());
        }
    
        /**
         * 获取当前时间字符串(HH:mm:ss)
         * @return
         */
        public static String getCurrentTimeStr() {
            return DateTimeFormatter.ofPattern(TimeFormatter.TIME_FORMATTER).format(currentLocalDateTime());
        }
    
        /**
         * 获取当前日期时间字符串(yyyy-MM-dd HH:mm:ss)
         * @return
         */
        public static String getCurrentDateTimeStr() {
            return DateTimeFormatter.ofPattern(TimeFormatter.DATETIME_FORMATTER).format(currentLocalDateTime());
        }
    
        /**
         * 将时间字符串转为自定义时间格式的LocalDateTime
         * @param time 需要转化的时间字符串
         * @param format 自定义的时间格式
         * @return
         */
        public static LocalDateTime convertStringToLocalDateTime(String time, String format) {
            return LocalDateTime.parse(time,DateTimeFormatter.ofPattern(format));
        }
    
        /**
         * 将LocalDateTime转为自定义的时间格式的字符串
         * @param localDateTime 需要转化的LocalDateTime
         * @param format 自定义的时间格式
         * @return
         */
        public static String convertLocalDateTimeToString(LocalDateTime localDateTime, String format) {
            return localDateTime.format(DateTimeFormatter.ofPattern(format));
        }
    
        /**
         * 将long类型的timestamp转为LocalDateTime
         * @param timestamp
         * @return
         */
        public static LocalDateTime convertTimestampToLocalDateTime(long timestamp) {
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp),ZoneId.systemDefault());
        }
    
        /**
         * 将LocalDateTime转为long类型的timestamp
         * @param localDateTime
         * @return
         */
        public static long convertLocalDateTimeToTimestamp(LocalDateTime localDateTime) {
            return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        }
    
        /**
         * 获取LocalDateTime的最大时间的字符串格式(yyyy-MM-dd HH:mm:ss)
         * @param localDateTime
         * @return
         */
        public static String getMaxDateTime(LocalDateTime localDateTime) {
            return convertLocalDateTimeToString(localDateTime.with(LocalTime.MAX),TimeFormatter.DATETIME_FORMATTER);
        }
    
        /**
         * 获取LocalDateTime的最小时间的字符串格式(yyyy-MM-dd HH:mm:ss)
         * @param localDateTime
         * @return
         */
        public static String getMinDateTime(LocalDateTime localDateTime) {
            return convertLocalDateTimeToString(localDateTime.with(LocalTime.MIN),TimeFormatter.DATETIME_FORMATTER);
        }
    
        /**
         * 获取LocalDate的最大时间的字符串格式(yyyy-MM-dd HH:mm:ss)
         * @param localDate
         * @return
         */
        public static String getMaxDateTime(LocalDate localDate) {
            return convertLocalDateTimeToString(localDate.atTime(LocalTime.MAX),TimeFormatter.DATETIME_FORMATTER);
    
        }
    
        /**
         * 获取LocalDate的最小时间的字符串格式(yyyy-MM-dd HH:mm:ss)
         * @param localDate
         * @return
         */
        public static String getMinDateTime(LocalDate localDate) {
            return convertLocalDateTimeToString(localDate.atTime(LocalTime.MIN),TimeFormatter.DATETIME_FORMATTER);
        }
    }

    3.常见方法

    .  adjustInto  调整指定的Temporal和当前LocalDateTime对
    .  atOffset    结合LocalDateTime和ZoneOffset创建一个
    .  atZone  结合LocalDateTime和指定时区创建一个ZonedD
    .  compareTo   比较两个LocalDateTime
    .  format  格式化LocalDateTime生成一个字符串
    .  from    转换TemporalAccessor为LocalDateTi
    .  get 得到LocalDateTime的指定字段的值
    .  getDayOfMonth   得到LocalDateTime是月的第几天
    .  getDayOfWeek    得到LocalDateTime是星期几
    . getDayOfYear    得到LocalDateTime是年的第几天
    . getHour 得到LocalDateTime的小时
    . getLong 得到LocalDateTime指定字段的值
    . getMinute   得到LocalDateTime的分钟
    . getMonth    得到LocalDateTime的月份
    . getMonthValue   得到LocalDateTime的月份,从1到12
    . getNano 得到LocalDateTime的纳秒数
    . getSecond   得到LocalDateTime的秒数
    . getYear 得到LocalDateTime的年份
    . isAfter 判断LocalDateTime是否在指定LocalDateT
    . isBefore    判断LocalDateTime是否在指定LocalDateT
    . isEqual 判断两个LocalDateTime是否相等
    . isSupported 判断LocalDateTime是否支持指定时间字段或单元
    . minus   返回LocalDateTime减去指定数量的时间得到的值
    . minusDays   返回LocalDateTime减去指定天数得到的值
    . minusHours  返回LocalDateTime减去指定小时数得到的值
    . minusMinutes    返回LocalDateTime减去指定分钟数得到的值
    . minusMonths 返回LocalDateTime减去指定月数得到的值
    . minusNanos  返回LocalDateTime减去指定纳秒数得到的值
    . minusSeconds    返回LocalDateTime减去指定秒数得到的值
    . minusWeeks  返回LocalDateTime减去指定星期数得到的值
    . minusYears  返回LocalDateTime减去指定年数得到的值
    . now 返回指定时钟的当前LocalDateTime
    . of  根据年、月、日、时、分、秒、纳秒等创建LocalDateTi
    . ofEpochSecond   根据秒数(从1970-01-0100:00:00开始)创建L
    . ofInstant   根据Instant和ZoneId创建LocalDateTim
    . parse   解析字符串得到LocalDateTime
    . plus    返回LocalDateTime加上指定数量的时间得到的值
    . plusDays    返回LocalDateTime加上指定天数得到的值
    . plusHours   返回LocalDateTime加上指定小时数得到的值
    . plusMinutes 返回LocalDateTime加上指定分钟数得到的值
    . plusMonths  返回LocalDateTime加上指定月数得到的值
    . plusNanos   返回LocalDateTime加上指定纳秒数得到的值
    . plusSeconds 返回LocalDateTime加上指定秒数得到的值
    . plusWeeks   返回LocalDateTime加上指定星期数得到的值
    . plusYears   返回LocalDateTime加上指定年数得到的值
    . query   查询LocalDateTime
    . range   返回指定时间字段的范围
    . toLocalDate 返回LocalDateTime的LocalDate部分
    . toLocalTime 返回LocalDateTime的LocalTime部分
    . toString    返回LocalDateTime的字符串表示
    . truncatedTo 返回LocalDateTime截取到指定时间单位的拷贝
    . until   计算LocalDateTime和另一个LocalDateTi
    . with    返回LocalDateTime指定字段更改为新值后的拷贝
    . withDayOfMonth  返回LocalDateTime月的第几天更改为新值后的拷贝
    . withDayOfYear   返回LocalDateTime年的第几天更改为新值后的拷贝
    . withHour    返回LocalDateTime的小时数更改为新值后的拷贝
    . withMinute  返回LocalDateTime的分钟数更改为新值后的拷贝
    . withMonth   返回LocalDateTime的月份更改为新值后的拷贝
    . withNano    返回LocalDateTime的纳秒数更改为新值后的拷贝
    . withSecond  返回LocalDateTime的秒数更改为新值后的拷贝
    . withYear    返回LocalDateTime年份更改为新值后的拷贝

    补充:

    package com.xx.dubbo.dubboservice.utils;
    
    import java.time.*;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.ChronoUnit;
    import java.time.temporal.TemporalAdjusters;
    import java.time.temporal.WeekFields;
    import java.util.Date;
    import java.util.Locale;
    
    /**
     * 日期工具
     * @description:
     * @author: 47
     * @time: 2020/5/6 9:43
     */
    public class DateUtil {
    
        //数据库格式的日期
        public static final String SQL_MONTH = "yyyy-MM";
        public static final String SQL_DATE = "yyyy-MM-dd";
        public static final String SQL_TIME = "yyyy-MM-dd HH:mm:ss";
        public static final String SQL_TIMESTAMP = "yyyy-MM-dd HH:mm:ss.SS";
    
        //斜杠格式的日期
        public static final String DATE = "yyyy/MM/dd";
        public static final String TIMESTAMP = "yyyy/MM/dd HH:mm:ss.SS";
        public static final String TIMESTAMP_SHORT = "yyyy/MM/dd HH:mm";
        public static final String TIME = "HH:mm:ss";
        public static final String TIME_SHORT = "HH:mm";
    
        //不常用日期格式
        public static final String CHINESEDATE = "yyyy年MM月dd日";
        public static final String DATE_TIME = "yyyyMMddHHmmss";
        public static final String DATE_TIME_DETAIL = "yyyyMMddHHmmssSS";
        public static final String DATE_DAY = "yyyyMMdd";
        public static final String DATE_HOUR = "yyyyMMddHH";
    
    
        /**
         * 防止被实例化
         */
        private DateUtil(){
    
        }
    
        /**
         * Date转LocalDateTime
         * 使用系统时区
         * @param date
         * @return
         */
        public static LocalDateTime dateToLocalDateTime(Date date){
            Instant instant = date.toInstant();
            return instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        }
    
        /**
         * LocalDateTime转Date
         * 使用系统时区
         * @param localDateTime
         * @return
         */
        public static Date localDateTimeToDate(LocalDateTime localDateTime){
            ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
            return Date.from(zdt.toInstant());
        }
    
        /**
         * 日期转字符串
         * @param localDateTime
         * @param pattern
         * @return
         */
        public static String dateTimeToStr(LocalDateTime localDateTime, String pattern) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            return localDateTime.format(formatter);
        }
    
        /**
         * 将字符串日期解析为java.time.LocalDateTime
         * @param dateTimeStr
         * @param pattern
         * @return
         */
        public static LocalDateTime strToLocalDateTime(String dateTimeStr, String pattern) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            return LocalDateTime.parse(dateTimeStr, formatter);
        }
    
        /**
         * 开始日期,补齐" 00:00:00"
         *
         * @param localDateTime
         * @return
         */
        public static LocalDateTime getStartDateTimeWithHMS(LocalDateTime localDateTime) {
            return LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MIN);
        }
    
        /**
         * 结束日期,补齐" 23:59:59"
         * @param localDateTime
         * @return
         */
        public static LocalDateTime getEndDateWithHMS(LocalDateTime localDateTime){
            return LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MAX);
        }
    
    
    
        public static LocalDateTime getAfterYears(LocalDateTime localDateTime, int count){
            return localDateTime.plusYears(count);
        }
    
        public static LocalDateTime getAfterMonths(LocalDateTime localDateTime, int count){
            return localDateTime.plusMonths(count);
        }
    
        public static LocalDateTime getAfterDays(LocalDateTime localDateTime, int count){
            return localDateTime.plusDays(count);
        }
    
        public static LocalDateTime getAfterMinutes(LocalDateTime localDateTime, int count){
            return localDateTime.plusMinutes(count);
        }
    
        public static LocalDateTime getAfterSeconds(LocalDateTime localDateTime, int count){
            return localDateTime.plusSeconds(count);
        }
    
    
    
        /**
         * 获得当前年的第一天
         * @param
         * @return
         */
        public static LocalDateTime getYearFirstDay(LocalDateTime localDateTime) {
            return localDateTime.with(TemporalAdjusters.firstDayOfYear());
        }
    
        /**
         * 获得当前年的最后一天
         * @param
         * @return
         */
        public static LocalDateTime getYearLastDay(LocalDateTime localDateTime) {
            return localDateTime.with(TemporalAdjusters.lastDayOfYear());
        }
    
    
        /**
         * 获得当前月的第一天
         * @param
         * @return
         */
        public static LocalDateTime getMonthFirstDay(LocalDateTime localDateTime) {
            return localDateTime.with(TemporalAdjusters.firstDayOfMonth());
        }
    
        /**
         * 获得当前月的最后一天
         * @param
         * @return
         */
        public static LocalDateTime getMonthLastDay(LocalDateTime localDateTime) {
            return localDateTime.with(TemporalAdjusters.lastDayOfMonth());
        }
    
    
        /**
         * 获得当前星期的第一天
         * @param localDateTime
         * @param locale 默认Locale.CHINA 周日为一周的第一天
         * @return
         */
        public static LocalDateTime getWeekFirstDay(LocalDateTime localDateTime, Locale locale) {
            return localDateTime.with(WeekFields.of(locale==null?Locale.CHINA:locale).dayOfWeek(),1);
        }
    
        /**
         * 获得当前星期的最后一天
         * @param localDateTime
         * @param locale 默认默认Locale.CHINA 周日为一周的第一天
         * @return
         */
        public static LocalDateTime getWeekLastDay(LocalDateTime localDateTime, Locale locale) {
            return localDateTime.with(WeekFields.of(locale==null?Locale.CHINA:locale).dayOfWeek(),7);
        }
    
    
    
        /**
         * 计算两个日期之间相差年数
         * @param smallDateTime 较小的时间
         * @param bigDateTime  较大的时间
         * @return 相差年数
         */
        public static int getYearDiff(LocalDateTime smallDateTime, LocalDateTime bigDateTime) {
            return (int)smallDateTime.until(bigDateTime, ChronoUnit.YEARS);
        }
    
        /**
         * 计算两个日期之间相差月数
         * @param smallDateTime 较小的时间
         * @param bigDateTime  较大的时间
         * @return 相差月数
         */
        public static int getMonthDiff(LocalDateTime smallDateTime, LocalDateTime bigDateTime) {
            return (int)smallDateTime.until(bigDateTime, ChronoUnit.MONTHS);
        }
    
        /**
         * 计算两个日期之间相差的天数
         * @param smallDateTime 较小的时间
         * @param bigDateTime  较大的时间
         * @return 相差天数
         */
        public static int getDayDiff(LocalDateTime smallDateTime, LocalDateTime bigDateTime){
            return (int)smallDateTime.until(bigDateTime, ChronoUnit.DAYS);
        }
    
        /**
         * 计算两个日期之间相差小时数
         * @param smallDateTime 较小的时间
         * @param bigDateTime  较大的时间
         * @return 相差小时数
         */
        public static int getHourDiff(LocalDateTime smallDateTime, LocalDateTime bigDateTime){
            return (int)smallDateTime.until(bigDateTime, ChronoUnit.HOURS);
        }
    
        /**
         * 计算两个日期之间相差分钟数
         * @param smallDateTime
         * @param bigDateTime
         * @return 相差分钟数
         */
        public static int getMinutesDiff(LocalDateTime smallDateTime, LocalDateTime bigDateTime){
            return (int)smallDateTime.until(bigDateTime, ChronoUnit.MINUTES);
        }
    
        /**
         * 计算两个日期之间相差秒数
         * @param smallDateTime
         * @param bigDateTime
         * @return 相差秒数
         */
        public static int getSecondsDiff(LocalDateTime smallDateTime, LocalDateTime bigDateTime){
            return (int)smallDateTime.until(bigDateTime, ChronoUnit.SECONDS);
        }
    
    
        public static void main(String[] args) {
            LocalDateTime now = LocalDateTime.now();
            System.out.println(getAfterMonths(now, 1));
        }
    
    }
  • 相关阅读:
    「SHOI2015」脑洞治疗仪
    LOJ 数列分块入门 8
    CF932F Escape Through Leaf
    NOIP2021游记总结
    [HEOI2016/TJOI2016]序列
    【模板】动态树(Link Cut Tree)
    LG P2839 [国家集训队]middle
    JZOJ 7377.欢乐豆
    JZOJ 7392. 【2021.11.17NOIP提高组联考】数 (ds)
    LOJ 数列分块入门 6
  • 原文地址:https://www.cnblogs.com/47Gamer/p/13817069.html
Copyright © 2011-2022 走看看