Java中的日期总结

        不管是在SE的应用也好,还是在Web应用中也好。我们常常需要用到时间,所以掌握时间的常用用法是很重要的。对于时间,我们最常用的操作无非就是:

  1. 获取当前时间
  2. 获取自定义的一个时间
  3. 对时间进行加减
  4. 判断时间的前后关系
  5. 对时间进行格式化

       Java中的时间可以分为绝对时间和人类时间。何谓绝对时间?众所周知,在Java中时间是用一个long型的整数保存的,绝对时间可以理解为这个long型整数;那何谓人类时间呢?人类时间就是你我都能看得懂的。

        不推荐使用之前的Date类、Calendar类,而是推荐使用Java8里Java.time包下的LocalDate、LocalTime、LocalDateTime等等

        这里给段代码,一切都一目了然了

/**
 * @ClassName Test
 * @Description TODO
 * @Author lzh
 * @Date 2021/7/22 20:11
 */

public class Test {
    public static void main(String[] args) throws InterruptedException {
        //绝对时间
        Instant start = Instant.now();
        Thread.sleep(1000);
        Instant end = Instant.now();
        //Duration表示两个绝对时间之间的间隔
        Duration between = Duration.between(start, end);
        //这个间隔可以换算成秒、小时、天等等
        long seconds = between.getSeconds();
        System.out.println(seconds);
        long l1 = between.toHours();
        System.out.println(l1);
        long l = between.toMillis();
        System.out.println(l);

        //人类时间
        //当前时间
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);

        //自定义时间
        LocalDate of = LocalDate.of(2001, 3, 8);
        System.out.println(of);

        //程序员日是每年的第256天 加减
        LocalDate localDate1 = LocalDate.of(2021, 1, 1).plusDays(255);
        System.out.println(localDate1);

        //这是一周的星期几
        int value = localDate1.getDayOfWeek().getValue();
        System.out.println(value);


        LocalDate independenceDay = LocalDate.of(2018, 6, 4);
        LocalDate christmas = LocalDate.of(2018, 11, 25);


        //人力时间计算间隔
        System.out.println("Until christmas:" + independenceDay.until(christmas));
        System.out.println("Until christmas:" + independenceDay.until(christmas, ChronoUnit.DAYS));

        //加减
        System.out.println(LocalDate.of(2016, 1, 31).plusMonths(1));
        System.out.println(LocalDate.of(2016, 3, 31).minusMonths(1));

        DayOfWeek startOfLastMillennium = LocalDate.of(1900, 1, 1).getDayOfWeek();
        System.out.println(startOfLastMillennium);
        System.out.println(startOfLastMillennium.getValue());

        //时间
        LocalTime now = LocalTime.now();
        System.out.println(now);
        LocalTime time = LocalTime.of(12, 0);
        System.out.println(time);


        LocalDateTime now1 = LocalDateTime.now();
        System.out.println(now1);

        //日期格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String format = formatter.format(now1);
        System.out.println(format);


    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值