项目总结70:LocalDate、LocalTime和LocalDateTime

项目总结70:LocalDate、LocalTime和LocalDateTime

START

LocalDate

    //日期
    public static void main(String[] args) {
        //1-创建当前日期
        LocalDate now = LocalDate.now();
        //2-创建指定日期
        LocalDate date = LocalDate.of(2020, 9, 1);
        //3-获取日期的具体数据
        System.out.println();
        System.out.println("当周的哪一天(英文): " + now.getDayOfWeek());
        System.out.println("当月的哪一天(数值): " + now.getDayOfMonth());
        System.out.println("当年的哪一天(数值): " + now.getDayOfYear());
        System.out.println("哪一月(英文): " + now.getMonth());
        System.out.println("哪一月(数值): " + now.getMonthValue());
        System.out.println("哪一年(数值): " + now.getYear());
        //4-修改时日期
        LocalDate newDate = now.withYear(2019).withMonth(8).withDayOfMonth(31);
        //5-格式化日期
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        System.out.println(newDate.format(dtf));
        //6-日期计算
        LocalDate yesterdayDate = now.minusDays(1);
        LocalDate tomorrowDate = now.plusDays(1);
    }

LocalTime

    public static void main(String[] args) {
        //1-当前时间
        LocalTime now = LocalTime.now();
        //2-创建指定时间
        LocalTime newTime = LocalTime.of(10, 10, 10);//10:10:10
        //3-获取时间具体数据
        System.out.println("时: " + now.getHour());
        System.out.println("分: " + now.getMinute());
        System.out.println("秒: " + now.getSecond());
        //4-格式化时间
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
        System.out.println(now.format(dtf));

    }

LocalDateTime

    //日期+时间
    public static void main(String[] args) {

        //LocalDateTime拥有LocalDate和LocalTime的大部分方法

        //1-获取当前日期+时间
        LocalDateTime localDateTime = LocalDateTime.now();//使用LocalDateTime直接获取
        LocalDate nowDate = LocalDate.now();
        LocalTime nowTime = LocalTime.now();
        LocalDateTime localDateTime1 = nowDate.atTime(nowTime);//通过日期关联时间过去
        LocalDateTime localDateTime2 = nowTime.atDate(nowDate);//通过时间关联提起获取
        //2-获取指定日期+时间
        LocalDateTime newDateTime = LocalDateTime.of(2019, 8, 31, 10, 10, 10);
    }

END

原文地址:https://www.cnblogs.com/wobuchifanqie/p/13646100.html