欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Java】Java8日期处理实践

程序员文章站 2022-05-27 16:11:48
...

Java8日期处理实践

Java8日期API简介

Java 8 推出了全新的日期时间API,在教程中我们将通过一些简单的实例来学习如何使用新API。新API基于ISO标准日历系统,java.time包下的所有类都是不可变类型而且线程安全。
【Java】Java8日期处理实践

示例代码

package util;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class TimeFormat {
    // 获取今天的日期
    public static void getTodayDate() {
        LocalDate today = LocalDate.now();
        System.out.println("今天的日期:" + today);
    }

    // 获取今天的年、月、日信息
    public static void getYearMonthDay() {
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        System.out.println("年:" + year + ",月:" + month + ",日:" + day);
    }

    // 处理特定日期
    public static void reBuildDate() {
        LocalDate date = LocalDate.of(2020, 2, 6);
        System.out.println("自定义日期:" + date);
    }

    // 判断两个日期是否相等
    public static void judgeEqual() {
        LocalDate date1 = LocalDate.now();
        LocalDate date2 = LocalDate.of(2020, 1, 11);
        if (date1.equals(date2)) {
            System.out.println("时间相等");
        } else {
            System.out.println("时间不相等");
        }
    }

    // 检查像日期这种周期性事件
    public static void judgeEvent() {
        LocalDate date1 = LocalDate.now();
        LocalDate date2 = LocalDate.of(2019, 2, 11);
        MonthDay birthday = MonthDay.of(date2.getMonth(), date1.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(date1);
        if (currentMonthDay.equals(birthday)) {
            System.out.println("是你的生日");
        } else {
            System.out.println("你的生日还没到");
        }
    }

    // 获取当前时间
    public static void getTime() {
        LocalTime time = LocalTime.now();
        System.out.println("获取当前的时间,不含有日期:" + time);
    }

    // 获取当前时间2
    public static void getTime2() {
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(3);
        System.out.println("三个小时后的时间:" + newTime);
    }

    // 计算一周后的日期
    public static void getTimeAfterWeek() {
        LocalDate today = LocalDate.now();
        System.out.println("今天的日期为:" + today);
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("一周后的日期为:" + nextWeek);
    }

    // 计算一年前或一年后的日期
    public static void getTimeAfterYear() {
        LocalDate today = LocalDate.now();
        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("一年前的日期:" + previousYear);
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("一年后的日期:" + nextYear);
    }

    // Clock时钟类
    public static void clockClass() {
        Clock clock = Clock.systemUTC();
        System.out.println("Clock:" + clock.millis());

        Clock defaultClock = Clock.systemDefaultZone();
        System.out.println("Clock: " + defaultClock.millis());
    }

    // 判断一个日期早于还是晚于一个日期
    public static void judgeBefororAfter() {
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = LocalDate.of(2020, 2, 12);
        if (tomorrow.isAfter(today)) {
            System.out.println("之后的日期:" + tomorrow);
        }
        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
        if (yesterday.isBefore(today)) {
            System.out.println("之前的日期:" + yesterday);
        }
    }

    // 处理时区
    public static void getTimeZone() {
        ZoneId america = ZoneId.of("America/New_York");
        LocalDateTime localDateTime = LocalDateTime.now();
        ZonedDateTime dateTimeInNewYork = ZonedDateTime.of(localDateTime, america);
        System.out.println("Current date and time in a particular timezone:" + dateTimeInNewYork);
    }

    // 表示信用卡到期之类的方法
    public static void creditCardExpiry() {
        YearMonth currentYearMonth = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
        YearMonth creditCardExpiry = YearMonth.of(2020, Month.FEBRUARY);
        System.out.printf("Your credit card expirds on %s %n", creditCardExpiry);
    }

    // 检查闰年
    public static void judgeIsLeapYear() {
        LocalDate today = LocalDate.now();
        if (today.isLeapYear()) {
            System.out.println("This is a Leap Year");
        } else {
            System.out.println("This is not a Leap Year");
        }
    }

    // 计算两个日期之间的天数和月数
    public static void getDaysAndMonthsBetweenTwoDate() {
        LocalDate today = LocalDate.now();
        LocalDate java8Release = LocalDate.of(2020, 2, 13);
        Period periodToNextJavaRelease = Period.between(today, java8Release);
        System.out.println("Months left between today and java 8 Release:" + periodToNextJavaRelease.getMonths());
    }

    // 获取当前的时间戳
    public static void getTimeStamp() {
        Instant timeStamp = Instant.now();
        System.out.println("What is the value of this instant " + timeStamp.toEpochMilli());
    }

    // 如何使用预定义的格式化工具解析或格式化日期
    public static void formatDate() {
        String dayAfterTomorrow = "20200211";
        LocalDate formatted = LocalDate.parse(dayAfterTomorrow, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(dayAfterTomorrow + " 格式化之后的日期为:" + formatted);
    }

    // 字符串互转日期类型
    public static void string2date() {
        LocalDateTime date = LocalDateTime.now();
        DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        // 日期转字符串
        String str = date.format(format1);
        System.out.println("日期转字符串:" + str);
        DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        // 字符串转日期
        LocalDate date2 = LocalDate.parse(str, format2);
        System.out.println("日期类型:" + date2);
    }

    public static void main(String[] args) {
        getTimeStamp();
        getTimeZone();
        getYearMonthDay();
        getDaysAndMonthsBetweenTwoDate();
        getTime();
        getTime2();
        judgeBefororAfter();
        judgeEqual();
        judgeEvent();
        judgeIsLeapYear();
    }
}