天天看点

java8 新的日期类型用法

import java.time.*;

import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Objects;

/**
 * java8 新的日期类型用法 LocalDate、LocalTime、LocalDateTime用法
 *
 * @author slliver
 * @date 2019-01-09 15:49
 */
public class LocalDateUtils {

    /**
     * 获取当前时间
     */
    public static void getLocalDateTest() {
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);
        LocalTime localTime = LocalTime.now();
        System.out.println(localTime);
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);
    }


    /**
     * 根据指定日期/时间创建对象
     */
    public static void createLocalDateTest() {
        LocalDate localDate1 = LocalDate.now();
        LocalDate localDate = LocalDate.of(2020, 1, 9);
        System.out.println(localDate);
        System.out.println(Objects.equals(localDate1, localDate));

        LocalTime localTime = LocalTime.of(13, 35, 22);
        System.out.println(localTime);

        LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 9, 13, 35, 22);
        System.out.println(localDateTime);
    }

    /**
     * 日期时间的加减
     * 对于LocalDate,只有精度大于或等于日的加减,如年、月、日;
     * 对于LocalTime,只有精度小于或等于时的加减,如时、分、秒、纳秒;
     * 对于LocalDateTime,则可以进行任意精度的时间相加减;
     */
    public static void locaLDateAddAndSubTest() {
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("当前时间 == >> " + localDateTime);
        //以下方法的参数都是long型,返回值都是LocalDateTime
        LocalDateTime plusYearsResult = localDateTime.plusYears(2L);
        System.out.println("当前时间加上两年后的日期 == >>> " + plusYearsResult);
        LocalDateTime plusMonthsResult = localDateTime.plusMonths(3L);
        System.out.println("当前时间加上3个月后的日期 == >>> " + plusMonthsResult);
        LocalDateTime plusDaysResult = localDateTime.plusDays(7L);
        System.out.println("当前时间加上7天之后的日期 == >>> " + plusDaysResult);
        LocalDateTime plusHoursResult = localDateTime.plusHours(2L);
        System.out.println("当前时间加上2小时之后的日期 == >>> " + plusHoursResult);
        LocalDateTime plusMinutesResult = localDateTime.plusMinutes(20L);
        System.out.println("当前时间加上20分钟之后的日期 == >>> " + plusMinutesResult);
        LocalDateTime plusSecondsResult = localDateTime.plusSeconds(120L);
        System.out.println("当前时间加上120秒之后的日期 == >>> " + plusSecondsResult);

        System.out.println("当前时间是 : " + localDateTime + "\n"
                + "当前时间加2年后为 : " + plusYearsResult + "\n"
                + "当前时间加3个月后为 : " + plusMonthsResult + "\n"
                + "当前时间加7日后为 : " + plusDaysResult + "\n"
                + "当前时间加2小时后为 : " + plusHoursResult + "\n"
                + "当前时间加20分钟后为 : " + plusMinutesResult + "\n"
                + "当前时间加120秒后为 : " + plusSecondsResult + "\n"
        );

        System.out.println("==================================================================");

        // 也可以以另一种方式来相加减日期,即plus(long amountToAdd, TemporalUnit unit) 参数1 : 相加的数量, 参数2 : 相加的单位
        LocalDateTime nextMonth = localDateTime.plus(1, ChronoUnit.MONTHS);
        LocalDateTime nextYear = localDateTime.plus(1, ChronoUnit.YEARS);
        LocalDateTime nextWeek = localDateTime.plus(1, ChronoUnit.WEEKS);
        System.out.println("now : " + localDateTime + "\n"
                + "nextYear : " + nextYear + "\n"
                + "nextMonth : " + nextMonth + "\n"
                + "nextWeek :" + nextWeek + "\n"
        );
        System.out.println("==================================================================");
    }

    /**
     * 将年、月、日等修改为指定的值,并返回新的日期(时间)对象
     */
    public static void updateYearMonthDay() {
        LocalDate localDate = LocalDate.now();
        // 当前时间基础上,指定本年当中的第几天,取值范围为1-365,366
        LocalDate withDayOfYearResult = localDate.withDayOfYear(200);
        // 当前时间基础上,指定本月当中的第几天,取值范围为1-29,30,31
        LocalDate withDayOfMonthResult = localDate.withDayOfMonth(5);
        // 当前时间基础上,直接指定年份
        LocalDate withYearResult = localDate.withYear(2017);
        // 当前时间基础上,直接指定月份
        LocalDate withMonthResult = localDate.withMonth(5);

        System.out.println("当前时间是 : " + localDate + "\n"
                + "指定本年当中的第200天 : " + withDayOfYearResult + "\n"
                + "指定本月当中的第5天 : " + withDayOfMonthResult + "\n"
                + "直接指定年份为2017 : " + withYearResult + "\n"
                + "直接指定月份为5月 : " + withMonthResult + "\n"
        );
    }

    /**
     * 获取日期的年月日周时分秒
     */
    public static void getEveryLocalDateTime() {
        LocalDateTime localDateTime = LocalDateTime.now();
        int dayOfYear = localDateTime.getDayOfYear();
        int dayOfMonth = localDateTime.getDayOfMonth();
        DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();

        System.out.println("今天是 " + localDateTime + "\n"
                + "本年当中第 " + dayOfYear + "天" + "\n"
                + "本月当中第 " + dayOfMonth + "天" + "\n"
                + "本周中星期" + dayOfWeek.getValue() + ", -即 ==>> " + dayOfWeek + "\n");
    }

    /**
     * 时间日期前后的比较与判断
     */
    public static void compareBeforeOrAfter() {
        // 判断两个时间点的前后
        LocalDate localDate1 = LocalDate.of(2018, 8, 8);
        LocalDate localDate2 = LocalDate.of(2019, 1, 9);
        boolean date1IsBeforeDate2 = localDate1.isBefore(localDate2);
        System.out.println("date1IsBeforeDate2 : " + date1IsBeforeDate2);

        LocalDate localDate3 = LocalDate.now();
        LocalDate localDate4 = LocalDate.now();
        boolean date1IsBeforeDate3 = localDate3.isBefore(localDate4);
        System.out.println("date1IsBeforeDate3 : " + date1IsBeforeDate3);
    }

    /**
     * 判断是否为闰年
     */
    public static boolean isLeapYear() {
        LocalDate now = LocalDate.now();
        boolean isLeapYear = now.isLeapYear();
        System.out.println("当前日期 : " + now + ", 当前日期是否为闰年 == >>>  " + now.isLeapYear());
        return isLeapYear;
    }

    /**
     * java8时钟
     */
    public static void testClock() {
        //返回当前时间,根据系统时间和UTC
        Clock clock = Clock.systemUTC();
        // 运行结果: SystemClock[Z]
        System.out.println(clock);
    }

    /**
     * 时间戳
     * 事实上Instant就是java8以前的Date,可以使用以下两个类中的方法在这两个类型之间进行转换,
     * 比如Date.from(Instant)就是用来把Instant转换成java.util.date的,而new Date().toInstant()就是将Date转换成Instant的
     */
    public static void testInstant() {
        Instant instant1 = Instant.now();
        // 2019-06-08T16:50:19.174Z
        System.out.println("instant1 == >> " + instant1);
        Date date = Date.from(instant1);
        Instant instant2 = date.toInstant();
        // Sun Jun 09 00:50:19 CST 2019
        System.out.println("date == >> " + date);
        System.out.println("instant2 == >> " + instant2);
    }


    /**
     * 计算日期间隔
     * Period:用于计算两个“日期”间隔
     */
    public static void calDatePeriod() {
        System.out.println("******************************************************************************************");
        // 计算两个日期的日期间隔-年月日
        LocalDate date1 = LocalDate.of(2019, 12, 19);
        LocalDate date2 = LocalDate.of(2020, 1, 9);
        // 内部是用date2-date1,所以得到的结果是负数
        Period period = Period.between(date1, date2);
        System.out.println("相差年数 : " + period.getYears());
        System.out.println("相差月数 : " + period.getMonths());
        System.out.println("相差日数 : " + period.getDays());

        // 还可以这样获取相差的年月日
        System.out.println("******************************************************************************************");
        long years = period.get(ChronoUnit.YEARS);
        long months = period.get(ChronoUnit.MONTHS);
        long days = period.get(ChronoUnit.DAYS);
        System.out.println("相差的年月日分别为 : " + years + "," + months + "," + days);
        // 注意,当获取两个日期的间隔时,并不是单纯的年月日对应的数字相加减,而是会先算出具体差多少天,在折算成相差几年几月几日的
        System.out.println("******************************************************************************************");
    }

    /**
     * 计算时间间隔
     * Duration:用于计算两个“时间”间隔
     */
    public static void calTimePeriod() {
        LocalDateTime date3 = LocalDateTime.of(2019, 12, 30, 15, 03, 00);
        LocalDateTime date4 = LocalDateTime.now();
        Duration duration = Duration.between(date3, date4);
        System.out.println(date3 + " 与 " + date4 + " 间隔  " + "\n"
                + " 天 :" + duration.toDays() + "\n"
                + " 时 :" + duration.toHours() + "\n"
                + " 分 :" + duration.toMinutes() + "\n"
                + " 毫秒 :" + duration.toMillis() + "\n"
                + " 纳秒 :" + duration.toNanos() + "\n"
        );
        // 注意,并没有获得秒差的,但既然可以获得毫秒,秒就可以自行获取了
    }

    /**
     * 获取时间戳
     * 当计算程序的运行时间时,应当使用时间戳Instant
     */
    public static void getInstant() throws InterruptedException {
        Instant ins1 = Instant.now();
        for (int i = 0; i < 10000000; i++) {
            //循环一百万次
        }
        Instant ins2 = Instant.now();
        Duration duration1 = Duration.between(ins1, ins2);
        System.out.println("程序1运行耗时为 : " + duration1.toMillis() + "毫秒");

        LocalDateTime date1 = LocalDateTime.now();
        for (int i = 0; i < 100; i++) {
            Thread.sleep(100L);
        }
        LocalDateTime date2 = LocalDateTime.now();

        Duration duration2 = Duration.between(date1, date2);
        long periodMillis = duration2.toMillis();
        System.out.println("程序2运行耗时为 : " + periodMillis + "毫秒" + ", 相当于 == >> " + periodMillis / 1000 + " 秒");
    }


    /**
     * 时间日期的格式化(格式化后返回的类型是String)DateTimeFormatter的格式很多,想看自己去源码查看
     */
    public static String format(LocalDateTime localDateTime, String pattern) {
        // 使用我们自动以格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern(pattern);
        // 使用jdk自身配置好的日期格式
//        DateTimeFormatter formatter1 = DateTimeFormatter.ISO_LOCAL_TIME;
        String dateTimeStr = formatter1.format(localDateTime);
        return dateTimeStr;
    }

    /**
     * 将时间字符串形式转化为日期对象
     */
    public static LocalDateTime parse(String datetime, String pattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime localDateTime = LocalDateTime.parse(datetime, dtf);
        return localDateTime;
    }

    /**
     * 当前时间戳转日期
     */
    public static String parseCurrentInstantToDate(String pattern) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        String longToDateTime = df.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.of("Asia/Shanghai")));
        return longToDateTime;
    }

    /**
     * 指定时间戳转日期
     */
    public static String parseInstantToDate(long instantMillis, String pattern) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        String longToDateTime = df.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(instantMillis), ZoneId.of("Asia/Shanghai")));
        return longToDateTime;
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("******************************************************************************************");
        String pattern = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime now = LocalDateTime.now();
        format(now, pattern);
        String patternDate = "yyyy-MM-dd";
        format(now, patternDate);
        String patternTime = "HH:mm:ss";
        format(now, patternTime);


        System.out.println("******************************************************************************************");
        String datetime = "2018-01-13 21:27:30";
        LocalDateTime localDateTime = parse(datetime, pattern);
        System.out.println("字符串格式化日期后 == >>> " + localDateTime);
        System.out.println("字符串格式化日期后在格式化成字符串 == >>> " + format(localDateTime, pattern));

        System.out.println("******************************************************************************************");
        String instantDateStr = parseCurrentInstantToDate(pattern);
        System.out.println("当前时间戳转日期字符串形式 == >>> " + instantDateStr);
        LocalDateTime instantDate = parse(instantDateStr, pattern);
        System.out.println("当前时间戳转日期日期对象形式 == >>> " + instantDate);


        System.out.println("******************************************************************************************");
        Instant instant = Instant.now();
        String instantDateStr2 = parseInstantToDate(instant.toEpochMilli(), pattern);
        System.out.println("指定时间戳转日期日期对象形式 == >>> " + instantDateStr2);
        long instantMillis = 1566454043790L;
        String instantDateStr3 = parseInstantToDate(instantMillis, pattern);
        System.out.println("指定时间戳转日期日期对象形式 == >>> " + instantDateStr3);
    }
}
      

继续阅读