java8 LocalDate

1 LocalDate转换成Date

LocalDate nowLocalDate = LocalDate.now();
Date date = Date.from(nowLocalDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());

2 LocalDateTime转换成LocalDate

LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = LocalDate.from(localDateTime);

3 比较大小

    public static void main(String[] args) {
        // 今天
        LocalDate today = LocalDate.now();
        // 明天
        LocalDate tomorrow = today.plusDays(1);
        
        // true-大于;false-不大于
        System.out.println(today.isBefore(tomorrow));
        
        // true-小于;false-大于
        System.out.println(today.isAfter(tomorrow));
        
        // true-相等;false-不相等
        System.out.println(today.equals(LocalDate.now()));
    }
true
false
true

4 获取年,月,日,周几

    public static void main(String[] args) {
        // 获取当前时间
        LocalDate localDateTime = LocalDate.now();
        System.out.println("当前时间为:" + localDateTime);
        // 获取当前月份
        System.out.println("当前月份为:" + localDateTime.getMonthValue());
        // 获取当前日期
        System.out.println("当前日期为:" + localDateTime.getDayOfMonth());
        // 今天是周几
        System.out.println("今天是周几:" + localDateTime.getDayOfWeek().getValue());
    }
当前时间为:2021-04-30
当前月份为:4
当前日期为:30
今天是周几:5

5 获取前一天,后一天

    public static void main(String[] args) {
        // 今天
        LocalDate today = LocalDate.now();
        System.out.println(today);
        // 昨天
        LocalDate yestDay = today.plusDays(-1);
        System.out.println(yestDay);
        // 明天
        LocalDate tomorrow = today.plusDays(1);
        System.out.println(tomorrow);
    }
2021-04-30
2021-04-29
2021-05-01

6 Long时间转LocalDate

public static LocalDate long2LocalDate(long time) {
        ZonedDateTime zonedDateTime = new Date(time).toInstant().atZone(ZoneId.systemDefault());
        return zonedDateTime.toLocalDate();
}

7 Long时间转LocalDateTime

public static LocalDateTime long2LocalDateTime(long time) {
        ZonedDateTime zonedDateTime = new Date(time).toInstant().atZone(ZoneId.systemDefault());
        return zonedDateTime.toLocalDateTime();
}

8 LocalDate转Long

    public static long localDate2Long(LocalDate localDate) {
        return localDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

8 LocalDateTime转Long

public static long localDateTime2Long(LocalDateTime localDateTime) {
        return localDateTime.toInstant(ZONE_OFFSET).toEpochMilli();
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值