java8的时间处理类

从Java 8之后,Java里面添加了许多的新特性,其中一个最常见也是最实用的便是日期处理的类——LocalDate。

新增的日期jar主要有三种:

java.time.LocalDate ->只对年月日做出处理

java.time.LocalTime ->只对时分秒纳秒做出处理

java.time.LocalDateTime ->同时可以处理年月日和时分秒

LocalDate基本方法

LocalDate today = LocalDate.now() //获取当前日期 年月日
LocalDate.of(2017, 07, 20); //生成对象
LocalDate.parse("2017-07-20");//解析字符串时间

LocalDate 与 String 之间的转换

        LocalDate today = LocalDate.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = today.format(fmt);
        String str = "2019-03-03";
        //指定转换格式
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");    
        //进行转换 
        LocalDate date = LocalDate.parse(str, fmt);

Date与LocalDate互转

/**
     * Date转LocalDate
     * @param date
     */
    public static LocalDate date2LocalDate(Date date) {
        if(null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * LocalDate转Date
     * @param localDate
     * @return
     */
    public static Date localDate2Date(LocalDate localDate) {
        if(null == localDate) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
获取该月的第一天,最后一天,该月的天数,时间段的天数

			//当月第一天
            LocalDate firstDay = start.with(TemporalAdjusters.firstDayOfMonth());
            //当月第一天
            firstDayOfMonth = firstDayOfMonth.withDayOfMonth(1);
			System.out.println("这个月的第一天: " + firstDayOfMonth);
            //当月最后一天
            LocalDate lastDay = start.with(TemporalAdjusters.lastDayOfMonth());
            //该月有多少天
            int dayOfMonth = lastDay.getDayOfMonth();
            //两个数据段的天数
			long count = end.toEpochDay() - start.toEpochDay() + 1;

判断今天是否是我生日:

LocalDate birthday = LocalDate.of(2009, 07, 20);
MonthDay birthdayMd = MonthDay.of(birthday.getMonth(), birthday.getDayOfMonth());
MonthDay today = MonthDay.from(LocalDate.now());
System.out.println("今天是否是我的生日: " + today.equals(birthdayMd));

LocalTime
LocalTime表示一个时间,而不是日期,下面介绍一下它的使用方法。

1.获取现在的时间,输出15:01:22.144

LocalTime now = LocalTime.now();
System.out.println("现在的时间: " + now);

2.将一个字符串时间解析为LocalTime,输出15:02

LocalTime nowTime = LocalTime.parse("15:02");
System.out.println("时间是: " + nowTime);

3.使用静态方法of创建一个时间

LocalTime nowTime = LocalTime.of(15, 02);
System.out.println("时间是: " + nowTime);

4.使用解析字符串的方式并添加一小时,输出16:02

LocalTime nextHour = LocalTime.parse("15:02").plus(1, ChronoUnit.HOURS);
System.out.println("下一个小时: " + nextHour);

5.获取时间的小时、分钟

int hour = LocalTime.parse("15:02").getHour();
System.out.println("小时: " + hour);
int minute = LocalTime.parse("15:02").getMinute();
System.out.println("分钟: " + minute);

6.我们也可以通过之前类似的API检查一个时间是否在另一个时间之前、之后

boolean isBefore = LocalTime.parse("15:02").isBefore(LocalTime.parse("16:02"));
boolean isAfter = LocalTime.parse("15:02").isAfter(LocalTime.parse("16:02"));
System.out.println("isBefore: " + isBefore);
System.out.println("isAfter: " + isAfter);

输出 isBefore: true, isAfter: false

7.在LocalTime类中也将每天的开始和结束作为常量供我们使用:

System.out.println(LocalTime.MAX);
System.out.println(LocalTime.MIN);
输出:

23:59:59.999999999
00:00

LocalDateTime
LocalDateTime是用来表示日期和时间的,这是一个最常用的类之一。

public class DemoLocalDateTime {
    public static void main(String[] args) {
        // static LocalDateTime	MAX:支持的最大本地日期时间(不包括时区)
        LocalDateTime max = LocalDateTime.MAX;// +999999999-12-31T23:59:59.999999999
        // static LocalDateTime	MIN:支持的最小本地日期时间(不包括时区)
        LocalDateTime min = LocalDateTime.MIN;// -999999999-01-01T00:00
        // static LocalDateTime	now():获取本地当前的日期时间(不含时区)
        LocalDateTime now = LocalDateTime.now(); // 2019-10-17T15:44:03.640
        // static LocalDateTime	now(Clock clock):从指定的时钟获取当前日期时间:这里用了UTC(世界标准时间)
        LocalDateTime nowClock = LocalDateTime.now(Clock.systemUTC()); // 2019-10-17T07:57:42.404
        // static LocalDateTime	now(ZoneId zone):从指定时区中的系统时钟获取当前日期时间
        LocalDateTime nowZoneId = LocalDateTime.now(ZoneId.systemDefault()); // 2019-10-17T16:09:04.127
        // static LocalDateTime	of(int year, int month, int dayOfMonth, int hour, int minute)
        // 从年,月,日,小时和分钟获取LocalDateTime的实例,并将秒和毫秒设置为零。
        LocalDateTime dateTime = LocalDateTime.of(2019, 10, 12, 6, 30); // 2019-10-12T06:30
        // static LocalDateTime	of(int year, int month, int dayOfMonth, int hour, int minute, int second)
        // static LocalDateTime	of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
        // static LocalDateTime	of(int year, Month month, int dayOfMonth, int hour, int minute)
        LocalDateTime localDateTime = LocalDateTime.of(2019, Month.OCTOBER, 12, 6, 30); // 2019-10-12T06:30
        // static LocalDateTime	of(int year, Month month, int dayOfMonth, int hour, int minute, int second)
        // static LocalDateTime	of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
        // static LocalDateTime	of(LocalDate date, LocalTime time):根据日期和时间获取LocalDateTime的实例
        LocalDateTime ldt = LocalDateTime.of(LocalDate.now(), LocalTime.now()); // 2019-10-17T16:33:42.714
        // static LocalDateTime	ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset)
        // 使用从1970-01-01T00:00:00Z的纪元开始的秒数获取LocalDateTime的实例,参数1:从纪元开始的秒数,参数2:毫秒数,参数3:时区
        LocalDateTime time = LocalDateTime.ofEpochSecond(55L, 99999, ZoneOffset.UTC); // 1970-01-01T00:00:55.000099999
        // static LocalDateTime	ofInstant(Instant instant, ZoneId zone)
        // 从Instant和区域ID获取LocalDateTime的实例。
        LocalDateTime ofInstant = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()); // 2019-10-17T16:54:50.941
        // static LocalDateTime	parse(CharSequence text)
        // 将字符串转化成日期时间对象
        LocalDateTime parse = LocalDateTime.parse("2019-10-17T16:54:50.941"); // 2019-10-17T16:54:50.941
        // static LocalDateTime	parse(CharSequence text, DateTimeFormatter formatter)
        // 使用特定格式化程序将文本字符串转成LocalDateTime对象
        LocalDateTime parse1 = LocalDateTime.parse("2019-10-17T16:54:50.941+01:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME); // 2019-10-17T16:54:50.941
        // LocalDateTime plus(long amountToAdd, TemporalUnit unit)
        // 在该日期时间基础上增加或减少一定时间,参数1:时间量,可以是负数,参数2:时间单位
        LocalDateTime plus = parse.plus(1L, ChronoUnit.HOURS); // 2019-10-17T17:54:50.941
        // LocalDateTime plus(TemporalAmount amountToAdd):在该时间基础上增加一定时间
        LocalDateTime plus1 = parse.plus(Period.ofDays(1)); // 2019-10-18T16:54:50.941
        // LocalDateTime    plusDays(long days):增加指定天数
        LocalDateTime plus2 = parse.plusDays(1L); // 2019-10-18T16:54:50.941
        // LocalDateTime	plusHours(long hours):增加指定小时数
        // LocalDateTime	plusMinutes(long minutes):增加指定分钟数
        // LocalDateTime	plusMonths(long months):增加指定月份数
        // LocalDateTime	plusNanos(long nanos):增加指定毫秒数
        // LocalDateTime	plusSeconds(long seconds):增加指定秒数
        // LocalDateTime	plusWeeks(long weeks):增加指定周数
        // LocalDateTime	plusYears(long years):增加指定年数

    }
}

日期格式化

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("默认格式化: " + now);
System.out.println("自定义格式化: " + now.format(dateTimeFormatter));
LocalDateTime localDateTime = LocalDateTime.parse("2017-07-20 15:27:44", dateTimeFormatter);
System.out.println("字符串转LocalDateTime: " + localDateTime);

也可以使用DateTimeFormatter的format方法将日期、时间格式化为字符串

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String dateString = dateTimeFormatter.format(LocalDate.now());
System.out.println("日期转字符串: " + dateString);

日期周期
Period类用于修改给定日期或获得的两个日期之间的区别。

给初始化的日期添加5天:

LocalDate initialDate = LocalDate.parse("2017-07-20");
LocalDate finalDate   = initialDate.plus(Period.ofDays(5));
System.out.println("初始化日期: " + initialDate);
System.out.println("加日期之后: " + finalDate);

周期API中提供给我们可以比较两个日期的差别,像下面这样获取差距天数:

long between = ChronoUnit.DAYS.between(initialDate, finalDate);
System.out.println("差距天数: " + between);

上面的代码会返回5,当然你想获取两个日期相差多少小时也是简单的。

与遗留代码转换
在之前的代码中你可能出现了大量的Date类,如何将它转换为Java8种的时间类呢?

Date和Instant互相转换

Date date = Date.from(Instant.now());
Instant instant = date.toInstant();

Date转换为LocalDateTime

LocalDateTime localDateTime = LocalDateTime.from(new Date());
System.out.println(localDateTime);

LocalDateTime localDateTime = Instant.ofEpochMilli(yunhuCallLogDTO.getRing().getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();

LocalDateTime转Date

Date date =
    Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

LocalDate转Date

Date date =
    Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值