美文网首页Java
LocalDateTime 代替 Date

LocalDateTime 代替 Date

作者: 愤怒的老照 | 来源:发表于2020-03-23 20:47 被阅读0次

背景

http://devgou.com/article/Java-Date/

  • Date如果不格式化,打印出的日期可读性差
    Tue Sep 10 09:34:04 CST 2019
  • 使用SimpleDateFormat对时间进行格式化,但SimpleDateFormat是线程不安全的
  • Date对时间处理比较麻烦,比如想获取某年、某月、某星期。(getYear、getMonth已弃用)

使用java8新的api,LocalDateTime

LocalDate,只有年月日

获取当前时间
LocalDate localDate = LocalDate.now();
System.out.println(localDate); //2020-03-23
构造指定的年月日
LocalDate localDate = LocalDate.of(2020, 3, 23);
System.out.println(localDate); //2020-03-23
获取年月日
LocalDate localDate = LocalDate.of(2020, 3, 23);
        int year = localDate.getYear();
        Month month = localDate.getMonth();
        int day = localDate.getDayOfMonth();
        DayOfWeek dayOfWeek = localDate.getDayOfWeek();

        System.out.println(year); //2020
        System.out.println(month.getValue()); //3
        System.out.println(day); //23
        System.out.println(dayOfWeek.getValue()); //1

LocalTime,只有时分秒

当前日期
LocalTime localTime1 = LocalTime.now();
System.out.println(localTime); //20:30:52.620
创建指定的日期
LocalTime localTime = LocalTime.of(20, 30, 52);
System.out.println(localTime); //20:30:52.620
获取时分秒
LocalTime localTime = LocalTime.of(20, 30, 52,200);
System.out.println(localTime.getHour()); // 20
System.out.println(localTime.getMinute()); // 30
System.out.println(localTime.getSecond()); //52
System.out.println(localTime.getNano()); // 200

LocalDateTime,相当于前两个结合

构造函数
LocalDateTime localDateTime = LocalDateTime.now(); 
LocalDateTime localDateTime1 = LocalDateTime.of(localDate, localTime); 
LocalDateTime localDateTime3 = localDate.atTime(localTime);
 LocalDateTime localDateTime4 = localTime.atDate(localDate);
获取localDate
LocalDate localDate = localDateTime.toLocalDate();
获取LocalTime
LocalTime localTime = localDateTime.toLocalTime();

LocalDateTime增加日期

LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
localDateTime.minusDays(1); //减少一天
localDateTime.plusDays(1); // 增加一天

localDateTime = localDateTime.withYear(2020); //修改为2020

格式化时间

LocalDate localDate = LocalDate.of(2020, 3, 23);
String s1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
String s2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
DateTimeFormatter dateTimeFormatter =   DateTimeFormatter.ofPattern("dd/MM/yyyy");
String s3 = localDate.format(dateTimeFormatter);

System.out.println(s1); //20200323
System.out.println(s2); //2020-03-23
System.out.println(s3); //23/03/2020

解析时间

LocalDate localDate1 = LocalDate.parse("20200323", DateTimeFormatter.BASIC_ISO_DATE);
LocalDate localDate2 = LocalDate.parse("2020-03-23", DateTimeFormatter.ISO_LOCAL_DATE);

相关文章

网友评论

    本文标题:LocalDateTime 代替 Date

    本文链接:https://www.haomeiwen.com/subject/urdgyhtx.html