java8之LocalDate的使用

核心代码一
import java.time.LocalDate;

public class DateFormat1 {
    public static void main(String[] args) throws Exception {
        LocalDate now = LocalDate.now();
        System.out.println("今天日期:" + now);
        // 获取年月日 周几
        System.out.println("年:"+now.getYear());
        System.out.println("月份:" + now.getMonth());
        System.out.println("月份(数字):" + now.getMonthValue());
        System.out.println("几号:" + now.getDayOfMonth());
        System.out.println("周几:" + now.getDayOfWeek());

        // 加减年份
        LocalDate localDate = now.plusYears(1);
        System.out.println("加后是哪一年:" + localDate.getYear());
        System.out.println("原来的是哪一年:" + now .getYear());

        // 日期比较
        System.out.println("isAfter(是否在某一年之后):" + localDate.isAfter(now));
    }


}


核心代码二
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateFormat2 {
    public static void main(String[] args) throws Exception {
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);

        // 线程安全
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dateTimeFormatter.format(localDateTime);
        System.out.println("格式化时间:" + format);
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String format2 = dateTimeFormatter2.format(localDateTime);
        System.out.println("格式化时间:" + format2);

        // 构造指定的时间对象
        LocalDateTime of = LocalDateTime.of(2020, 10, 10, 10, 20, 30);
        System.out.println("构造的时间:" + of);

        // 计算时间差
        System.out.println("计算时间差----------------------");
        LocalDateTime localDateTime1 = LocalDateTime.now();
        System.out.println(localDateTime1);
        LocalDateTime localDateTime2 = LocalDateTime.of(2020, 10, 10, 10, 20, 30);
        System.out.println(localDateTime2);

        Duration between = Duration.between(localDateTime2, localDateTime1);
        System.out.println("相差天数:" + between.toDays());
        System.out.println("相差小时:" + between.toHours());
        System.out.println("相差分钟:" + between.toMinutes());
        System.out.println("相差毫秒:" + between.toMillis());
        System.out.println("相差纳秒数:" + between.toNanos());
    }


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITzhongzi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值