Java日期与时间的常用操作

生活中,最使人疲惫的往往不是道路的遥远,而是心中的郁闷;最使人痛苦的往往不是生活的不幸,而是希望的破灭;最使人颓废的往往不是前途的坎坷,而是自信的丧失;最使人绝望的往往不是挫折的打击,而是心灵的死亡。所以我们要有自己的梦想,让梦想的星光指引着我们走出落漠,走出惆怅,带着我们走进自己的理想。

导读:本篇文章讲解 Java日期与时间的常用操作,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

获取/创建日期

    @Test
    public void testLocalDate() {
        //获取当前日期、年、月、日
        LocalDate localDate = LocalDate.now();
        // LocalDate.of() 创建任意日期
        //LocalDate localDate = LocalDate.of(2022, 10, 12);
        int year = localDate.getYear();
        int month = localDate.getMonthValue();
        int day = localDate.getDayOfMonth();
        //localDate : 2021-04-27  Year : 2021  Month : 4  day : 27 
        System.out.printf("localDate : %s  Year : %d  Month : %d  day : %d %n", localDate, year, month, day);

    }

获取/创建时间

    @Test
    public void testLocalTime() {
        //获取当前日期、年、月、日
        LocalTime localTime = LocalTime.now();
        // LocalTime.of() 创建任意时间
        //LocalTime localTime = LocalTime.of(2, 23, 23);
        int hour = localTime.getHour();
        int minute = localTime.getMinute();
        int second = localTime.getSecond();
        int nano = localTime.getNano();
        //localTime 18:23:35.625  hour 18  minute  23  second 35  nano 625000000
        System.out.printf("localTime %s  hour %d  minute  %d  second %d  nano %s %n", localTime, hour, minute, second, nano);
    }

获取/创建日期与时间

    public static void main(String[] args) {
        //创建当前日期与时间
        //LocalDateTime localDateTime = LocalDateTime.now();
        //创建指定的日期与时间
        LocalDateTime localDateTime = LocalDateTime.of(2022, 2, 23, 2, 3, 4);
        //获取年 月 日 时 分 秒。。。
        int year = localDateTime.getYear();
        int hour = localDateTime.getHour();
     
     	//Calendar可以用于获取并设置年、月、日、时、分、秒
        // 获取当前时间:
        Calendar calendar = Calendar.getInstance();
        int y = calendar.get(Calendar.YEAR);
        int m = 1 + calendar.get(Calendar.MONTH);
        int d = calendar.get(Calendar.DAY_OF_MONTH);
        int w = calendar.get(Calendar.DAY_OF_WEEK);
        int hh = calendar.get(Calendar.HOUR_OF_DAY);
        int mm = calendar.get(Calendar.MINUTE);
        int ss = calendar.get(Calendar.SECOND);
        int ms = calendar.get(Calendar.MILLISECOND);
        //2021-4-28 4 10:9:21.731
        System.out.println(y + "-" + m + "-" + d + " " + w + " " + hh + ":" + mm + ":" + ss + "." + ms);

        calendar.clear();

        calendar.set(Calendar.YEAR, 2022);
        // 设置9月:注意8表示9月
        calendar.set(Calendar.MONTH, 8);
        calendar.set(Calendar.DATE, 10);
        // 设置时间
        calendar.set(Calendar.HOUR_OF_DAY, 21);
        calendar.set(Calendar.MINUTE, 22);
        calendar.set(Calendar.SECOND, 23);

        //Calendar.getTime()可以将一个Calendar对象转换成Date对象
        Date date = calendar.getTime();

        //2022-09-10 21:22:23
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
    }

日期与时间的加减

ChronoUnit类声明了一些时间单位

    /**
     * 日期与时间的加减
     */
    @Test
    public void testPlusAndMinus(){
        LocalDate localDate = LocalDate.now();
        LocalDate aYearAgo = localDate.minus(1, ChronoUnit.YEARS);
        LocalDate oneYearLater = localDate.plus(1, ChronoUnit.YEARS);
        //localDate 2021-04-27 aYearAgo 2020-04-27 oneYearLater 2022-04-27 
        System.out.printf("localDate %s aYearAgo %s oneYearLater %s %n", localDate,aYearAgo,oneYearLater);

        LocalTime localTime = LocalTime.now();
        LocalTime aHoursAgo = localTime.minus(1, ChronoUnit.HOURS);
        LocalTime oneHoursLater = localTime.plus(1, ChronoUnit.HOURS);
        //localTime 18:02:37.598 oneHoursLater 17:02:37.598 oneHoursLater 19:02:37.598 
        System.out.printf("localTime %s oneHoursLater %s oneHoursLater %s %n", localTime,aHoursAgo,oneHoursLater);
    }
    @Test
    public void testPlusAndMinusMethod() {
        //获取当前日期
        LocalDate localDate = LocalDate.now();
        //增加年 月 周 日
        LocalDate plusYears = localDate.plusYears(1);
        LocalDate plusMonths = localDate.plusMonths(1);
        LocalDate plusWeeks = localDate.plusWeeks(1);
        LocalDate plusDays = localDate.plusDays(1);
        //localDate 2021-04-27  plusYears 2022-04-27  plusMonths 2021-05-27  plusWeeks 2021-05-04  plusDays 2021-04-28
        System.out.printf("localDate %s  plusYears %s  plusMonths %s  plusWeeks %s  plusDays %s %n", localDate, plusYears, plusMonths, plusWeeks, plusDays);

        //减少年 月 周 日
        LocalDate minusYears = localDate.minusYears(1);
        LocalDate minusMonths = localDate.minusMonths(1);
        LocalDate minusWeeks = localDate.minusWeeks(1);
        LocalDate minusDays = localDate.minusDays(1);
        //localDate 2021-04-27  minusYears 2020-04-27  minusMonths 2021-03-27  minusWeeks 2021-04-20  minusDays 2021-04-26
        System.out.printf("localDate %s  minusYears %s  minusMonths %s  minusWeeks %s  minusDays %s %n", localDate, minusYears, minusMonths, minusWeeks, minusDays);

        //获取当前时间
        LocalTime localTime = LocalTime.now();
        //增加小时 分 秒 纳秒
        LocalTime plusHours = localTime.plusHours(1);
        LocalTime plusMinutes = localTime.plusMinutes(1);
        LocalTime plusSeconds = localTime.plusSeconds(1);
        LocalTime plusNanos = localTime.plusNanos(1);
        //localTime 18:16:22.448  plusHours 19:16:22.448  plusMinutes 18:17:22.448  plusSeconds 18:16:23.448  plusNanos 18:16:22.448000001
        System.out.printf("localTime %s  plusHours %s  plusMinutes %s  plusSeconds %s  plusNanos %s %n", localTime, plusHours, plusMinutes, plusSeconds, plusNanos);

        //减少小时 分 秒 纳秒
        LocalTime minusHours = localTime.minusHours(1);
        LocalTime minusMinutes = localTime.minusMinutes(1);
        LocalTime minusSeconds = localTime.minusSeconds(1);
        LocalTime minusNanos = localTime.minusNanos(1);
        //localTime 18:16:22.448  minusHours 17:16:22.448  minusMinutes 18:15:22.448  minusSeconds 18:16:21.448  minusNanos 18:16:22.447999999 
        System.out.printf("localTime %s  minusHours %s  minusMinutes %s  minusSeconds %s  minusNanos %s %n", localTime, minusHours, minusMinutes, minusSeconds, minusNanos);
    }

日期/时间的比较

   @Test
    public void dateComparison() {
        //获取当前日期、年、月、日
        LocalDate localDate = LocalDate.now();
        //创建任意日期 2021-04-01
        LocalDate localDateOf = LocalDate.of(2021, 4, 1);

        //判断日期是否相等
        if (!localDate.equals(localDateOf)) {
            //2021-04-27 != 2021-04-01
            System.out.println(localDate + " != " + localDateOf);
        }
        if (localDateOf.isBefore(localDate)) {
            //2021-04-01 < 2021-04-27
            System.out.println(localDateOf + " < " + localDate);
        }
        if (localDate.isAfter(localDateOf)) {
            //2021-04-27 > 2021-04-01
            System.out.println(localDate + " > " + localDateOf);
        }

		 //10:30:37.154
        LocalTime localTime = LocalTime.now();
        //10:30:10
        LocalTime localTimeOf = LocalTime.of(10, 30, 10);

        if (!localTime.equals(localTimeOf)) {
            //10:30:37.154 != 10:30:10
            System.out.println(localTime + " != " + localTimeOf);
        }
        if (localTime.isAfter(localTimeOf)) {
            //10:30:37.154 > 10:30:10
            System.out.println(localTime + " > " + localTimeOf);
        }
        if (localTimeOf.isBefore(localTime)) {
            //10:30:10 < 10:30:37.154
            System.out.println(localTimeOf + " < " + localTime);
        }

		LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTimeOf = LocalDateTime.of(2021, 4, 28, 8, 8, 8);
        if (localDateTime.isAfter(localDateTimeOf)){
            System.out.println(localDateTime + " > "+localDateTimeOf);
        }
    }

YearMonth与MonthDay

判断返回每月的天数

    @Test
    public void checkCardExpiry(){
        YearMonth yearMonth1 = YearMonth.now();
        int days1 = yearMonth1.lengthOfMonth();
        //yearMonth1 2021-04 30 
        System.out.printf("yearMonth1 %s %d %n", yearMonth1, days1);

        YearMonth yearMonth2 = YearMonth.of(2020, Month.JANUARY);
        int days2 = yearMonth2.lengthOfMonth();
        //yearMonth2 2020-01   31 
        System.out.printf("yearMonth2 %s  % d %n", yearMonth2,days2);
    }

判断每年都会发生的事件

    @Test
    public void formateDate(){
        LocalDate today = LocalDate.now();
        //LocalDate.of() 创建任意日期
        LocalDate dateOfBirth = LocalDate.of(1996, 6, 6);

        MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(today);

        if (currentMonthDay.equals(birthday)) {
            System.out.println("happyBirthday");
        } else {
            System.out.println("today is not your birthday");
        }
    }

ZonedDateTime时区

ZonedDateTime表示一个带时区的日期和时间

    @Test
    public void TestZonedDateTime() {
        //当前时区
        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        //设置时区
        ZoneId america = ZoneId.of("America/New_York");
        LocalDateTime localtDateAndTime = LocalDateTime.now();
        //当前日期 时间转换到特定时区下的日期 时间
        ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america);
        //zonedDateTime 2021-04-28T09:14:36.890+08:00[Asia/Shanghai] dateAndTimeInNewYork 2021-04-28T09:14:36.892-04:00[America/New_York]
        System.out.printf("zonedDateTime %s dateAndTimeInNewYork %s  %n", zonedDateTime, dateAndTimeInNewYork);
    }

时区转换

    public static void main(String[] args) {
        // 以中国时区获取当前时间:
        ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        //2021-04-28T10:49:08.475+08:00[Asia/Shanghai]
        System.out.println(zonedDateTime1);
        // 转换为纽约时间:
        ZonedDateTime zonedDateTime2 = zonedDateTime1.withZoneSameInstant(ZoneId.of("America/New_York"));
        //2021-04-27T22:49:08.475-04:00[America/New_York]
        System.out.println(zonedDateTime2);
    }

计算两个日期之间的天数和月数

 @Test
    public void calcDateDays(){
        LocalDate localDate1 = LocalDate.now();
        // 2022-07-10
        LocalDate localDate2 = LocalDate.of(2022, Month.JULY, 10);
        /**
         * 获取一个Period ,该Period由两个日期之间的年,月和天数组成。
         * 包括开始日期,但不包括结束日期。
         * 从2010-01-15到2011-03-18是一年零两个月零三天。
         */
        Period period = Period.between(localDate1, localDate2);
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();
        //localDate1 2021-04-28  localDate2 2022-07-10 years 1 months 2 days 12
        System.out.printf("localDate1 %s  localDate2 %s years %s months %s days %s  %n: ",localDate1,localDate2,years ,months,days );
    }

日期格式化

    public static void main(String[] args) {
        // 自定义格式化:
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        //2021/04/28 10:16:52
        System.out.println(dtf.format(LocalDateTime.now()));

        // 用自定义格式解析:
        LocalDateTime dt2 = LocalDateTime.parse("2022/04/28 15:20:21", dtf);
        //2022-04-28T15:20:21
        System.out.println(dt2);
    }

使用预定义的格式化工具去解析或格式化日期

    public void formateDate(){
        String strDate = "20210428";
        LocalDate localDate = LocalDate.parse(strDate, DateTimeFormatter.BASIC_ISO_DATE);
        //strDate 20210428 => localDate 2021-04-28 
        System.out.printf("strDate %s => localDate %s %n", strDate, localDate);
    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137065.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!