Java8 LocalDateTime的基本用法

一、新时间日期API常用、重要对象介绍:

  • ZoneId: 时区ID,用来确定Instant和LocalDateTime互相转换的规则
  • Instant: 用来表示时间线上的一个点(瞬时)
  • LocalDate: 表示没有时区的日期, LocalDate是不可变并且线程安全的
  • LocalTime: 表示没有时区的时间, LocalTime是不可变并且线程安全的
  • LocalDateTime: 表示没有时区的日期时间, LocalDateTime是不可变并且线程安全的
  • Clock: 用于访问当前时刻、日期、时间,用到时区
  • Duration: 用秒和纳秒表示时间的数量(长短),用于计算两个日期的“时间”间隔
  • Period: 用于计算两个“日期”间隔

1、LocalDate、LocalTime、LocalDateTime是新API里的基础对象

      LocalDate : 只含年月日的日期对象
      LocalTime :只含时分秒的时间对象
      LocalDateTime : 同时含有年月日时分秒的日期对象

二、API的使用

1、时间的获取与转换

1.1、获取当前时间

LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();

1.2、时间之间的转换

LocalDateTime dt = LocalDateTime.now(); // 当前日期和时间
LocalDate d = dt.toLocalDate(); // 转换到当前日期
LocalTime t = dt.toLocalTime(); // 转换到当前时间

 1.3、通过指定的日期和时间创建LocalDateTime,用of

LocalDate d2 = LocalDate.of(2020, 11, 30); // 2019-11-30
LocalTime t2 = LocalTime.of(15, 16, 17); // 15:16:17
LocalDateTime dt2 = LocalDateTime.of(2020, 11, 30, 15, 16, 17);
LocalDateTime dt3 = LocalDateTime.of(d2, t2);

1.4、日期字符串转LocalDateTime 

LocalDateTime dt = LocalDateTime.parse("2019-11-19T15:16:17");
LocalDate d = LocalDate.parse("2019-11-19");
LocalTime t = LocalTime.parse("15:16:17");

注意:ISO 8601规定的日期和时间分隔符是T。标准格式如下:

日期:yyyy-MM-dd
时间:HH:mm:ss
带毫秒的时间:HH:mm:ss.SSS
日期和时间:yyyy-MM-dd'T'HH:mm:ss
带毫秒的日期和时间:yyyy-MM-dd'T'HH:mm:ss.SSS

延伸:

DateTimeFormatter

如果要自定义输出的格式,或者要把一个非ISO 8601格式的字符串解析成LocalDateTime,可以使用新的DateTimeFormatter

import java.time.*;
import java.time.format.*;


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

        // 用自定义格式解析:
        LocalDateTime dt2 = LocalDateTime.parse("2020/10/20 15:16:17", dtf);
        System.out.println(dt2);
    }
}

 2、日期时间的加减

LocalDateTime

2.1、提供了对日期和时间进行加减的非常简单的链式调用:

  • 对于LocalDate,只有精度大于或等于日的加减,如年、月、日;
  • 对于LocalTime,只有精度小于或等于时的加减,如时、分、秒、纳秒;
  • 对于LocalDateTime,则可以进行任意精度的时间相加减;
LocalDateTime localDateTime = LocalDateTime.now();
//以下方法的参数都是long型,返回值都是LocalDateTime
LocalDateTime plusYearsResult = localDateTime.plusYears(2L);
LocalDateTime plusMonthsResult = localDateTime.plusMonths(3L);
LocalDateTime plusDaysResult = localDateTime.plusDays(7L);
LocalDateTime plusHoursResult = localDateTime.plusHours(2L);
LocalDateTime plusMinutesResult = localDateTime.plusMinutes(10L);
LocalDateTime plusSecondsResult = localDateTime.plusSeconds(10L);


//也可以以另一种方式来相加减日期,即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);

2.2、将年、月、日等修改为指定的值,并返回新的日期(时间)对象

(以下列出 LoalDate 与 LocalDateTime  对应的使用方法,LocalDateTime拥有以下所有方法)

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);


LocalTime localTime = LocalTime.now();
//当前时间基础上,直接指定小时
LocalTime withHourResult = localTime.withHour(1);
//当前时间基础上,直接指定分钟
LocalTime withMinuteResult = localTime.withMinute(15);
//当前时间基础上,直接指定秒
LocalTime withSecondResult = localTime.withSecond(20);

 

注意:调整月份时,会相应地调整日期,即把2019-10-31的月份调整为9时,日期也自动变为30

延伸:LocalDateTime还有一个通用的with()方法允许我们做更复杂的运算:

// 本月第一天0:00时刻:
LocalDateTime firstDay = LocalDate.now().withDayOfMonth(1).atStartOfDay();

// 本月最后1天:
LocalDate lastDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());

// 下月第1天:
LocalDate nextMonthFirstDay = LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth());

// 本月第1个周一:
LocalDate firstWeekday = LocalDate.now().with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));

2.3、获取日期的年月日周时分秒

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");

        
//获取当天时间的年月日时分秒
int year = localDateTime.getYear();
Month month = localDateTime.getMonth();
int day = localDateTime.getDayOfMonth();
int hour = localDateTime.getHour();
int minute = localDateTime.getMinute();
int second = localDateTime.getSecond();
System.out.println("今天是" + localDateTime + "\n"
        + "年 : " + year + "\n"
        + "月 : " + month.getValue() + "-即 "+ month + "\n"
        + "日 : " + day + "\n"
        + "时 : " + hour + "\n"
        + "分 : " + minute + "\n"
        + "秒 : " + second + "\n"
        );

2.4、时间日期前后的比较与判断

要判断两个LocalDateTime的先后,可以使用isBefore()isAfter()方法,对于LocalDateLocalTime类似

//判断两个时间点的前后
LocalDateTime now = LocalDateTime.now();
LocalDateTime target = LocalDateTime.of(2019, 11, 19, 8, 15, 0);
System.out.println(now.isBefore(target));
System.out.println(LocalDate.now().isBefore(LocalDate.of(2019, 11, 19)));
System.out.println(LocalTime.now().isAfter(LocalTime.parse("08:15:00")));

注意:LocalDateTime无法与时间戳进行转换,因为LocalDateTime没有时区,无法确定某一时刻。ZonedDateTime相当于LocalDateTime加时区的组合,它具有时区,可以与long表示的时间戳进行转换。

2.5、时间、日期间隔的计算

2.5.1、Period:用于计算两个“日期”间隔

//计算两个日期的日期间隔-年月日
LocalDate date1 = LocalDate.of(2020, 10, 21);
LocalDate date2 = LocalDate.of(2019, 9, 11);
//内部是用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);

注意:当获取两个日期的间隔时,并不是单纯的年月日对应的数字相加减,而是会先算出具体差多少天,在折算成相差几年几月几日的

2.5.2、Duration:用于计算两个“时间”间隔

//计算两个时间的间隔
System.out.println("-------------------------------");
LocalDateTime date3 = LocalDateTime.now();
LocalDateTime date4 = LocalDateTime.of(2018, 1, 13, 22, 30, 10);
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"
        );

 注意:并没有获得秒差,没有该方法,不过可以通过毫秒换算

  • 32
    点赞
  • 201
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值