Java 8 neue Zeit-API LocalDate/LocalDateTime

Ich nehme am „Nuggets·Starting Plan“ teil

Einführung

Im Projekt ist die Verwendung von Zeit von wesentlicher Bedeutung, und es gab vor Java 8 viele Probleme bei der Verwendung der Zeit-API Date und Calander . Daher hat jdk1.8 eine neue Zeit-API -> LocalDateTime eingeführt, die sehr einfach zu lösen ist Probleme durch die Verwendung der Zeit-API.

vorheriger Slot

  1. Es ist unpraktisch, Datum oder Kalender zur Darstellung der Zeit zu verwenden
 Date date = new Date(2022,1,1);
 System.out.println(date);

wird am Do. 01. Februar um 00:00:00 CST 3922 ausgegeben

Der Monat wird direkt in Feb geändert und das Jahr mit 1900 hinzugefügt

Wenn Sie den Kalender verwenden , um den Monat anzugeben, müssen Sie darauf achten, dass der Monat bei 0 beginnt, dh im Januar 0 verwenden oder die bereitgestellte Aufzählung verwenden

Calendar calendar = Calendar.getInstance();
calendar.set(2022, Calendar.AUGUST, 2);

Zu diesem Zeitpunkt ist der übergebene Wert des Kalenderjahres jedoch 2022, was mit dem Jahr übereinstimmt, was zu einer Inkonsistenz der beiden Zeit-APIs führt

  1. Der Status des Kalenders ist variabel und während der Berechnung muss ein neuer Kalender erstellt werden

Wenn der Kalender nach Vorgängen wie Hinzufügen zu einem neuen Kalender wird, können beim nächsten Vergleich Fehler auftreten

 calendar.add(Calendar.DAY_OF_MONTH, 1);

3. SimpleDateTimeFormat ist nicht threadsicher.

Daher wurde eine neue Zeit-API – LocalDateTime – veröffentlicht, um die oben genannten Probleme zu lösen

Einführung

Instanzen der Klassen LocalDate, LocalTime und LocalDateTime sind unveränderliche Objekte, die ein Datum, eine Uhrzeit, ein Datum bzw. eine Uhrzeit unter Verwendung des ISO-8601-Kalendersystems darstellen. Sie geben ein einfaches Datum oder eine einfache Uhrzeit an und enthalten keine aktuellen Zeitinformationen. Zeitzonenbezogene Informationen sind ebenfalls nicht enthalten. Wie der Name schon sagt, wird LocalDate hauptsächlich für Datumsangaben verwendet, LocalTime wird hauptsächlich für Uhrzeiten verwendet und LocalDateTime ist eine Kombination aus Uhrzeit und Datum.

Methodenübersicht

  • von: statische Factory-Methode.

  • Parsen: Statische Factory-Methode, Fokus auf Parsen.

  • get: 获取某些东西的值。

  • is: 检查某些东西的是否是true。

  • with: 不可变的setter等价物。

  • plus: 加一些量到某个对象。

  • minus: 从某个对象减去一些量。

  • to: 转换到另一个类型。

  • at: 把这个对象与另一个对象组合起来,例如: date.atTime(time)。

使用

  1. 获取LocalDateTime等对象

通过静态方法now() 获取

LocalDate now = LocalDate.now(); //获取当前的年月日  2023-05-07
System.out.println(now);

LocalTime now1 = LocalTime.now();//获取当前时间   13:05:46.609

System.out.println(now1);

LocalDateTime now2 = LocalDateTime.now();   //获取当前日期加时间  2023-05-07T13:05:46.609
System.out.println(now2);

通过of()指定年月日时分秒

LocalDate now = LocalDate.now(); //获取当前的年月日  2023-05-07
System.out.println(now);

LocalTime now1 = LocalTime.now();//获取当前时间   13:05:46.609

System.out.println(now1);

LocalDateTime now2 = LocalDateTime.now();   //获取当前日期加时间  2023-05-07T13:05:46.609
System.out.println(now2);

2. 获取对象相关参数,如年,月

LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int dayOfYear = now.getDayOfYear();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();

3. 格式化日期方法 format()以及DateTimeFormatter的使用

LocalDate now = LocalDate.now();
//JDK1.8 格式化日期的类 DateTimeFormatter
//指定格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String dateStr = now.format(formatter);
System.out.println(dateStr); // 2023年05月07日

LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
//把日期对象,格式化成日期字符串
String str = localDateTime.format(formatter2);
System.out.println(str); //2023年05月07日 13点57分53秒

4. 将LocalDateTime转换为LocalDate以及LocalTime

System.out.println(localDateTime.toLocalDate()); //2023-05-07
System.out.println(localDateTime.toLocalTime());// 13:57:53.061

5. 比较日期或时间


    // isAfter() 判断一个日期是否在指定日期之后
    // isBefore() 判断一个日期是否在指定日期之前
    // isEqual();
    // 判断两个日期是否相同
    // isLeapYear() 判断是否是闰年注意是LocalDate类中的方法
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime of = LocalDateTime.of(2023, 5, 7,14,0,0);

    System.out.println("当前时间为"+now); //当前时间为2023-05-07T14:04:18.676

    boolean after = now.isAfter(of);
    System.out.println(after);  // true

    boolean before = of.isBefore(now);
    System.out.println(before); //true

    boolean equal = now.isEqual(of);
    System.out.println(equal); //false

    boolean equal1 = of.isEqual(of);
    System.out.println(equal1); //true


    //判断是不是闰年
    boolean leapYear = now.toLocalDate().isLeapYear();
    System.out.println(leapYear); //false

月份的比较会特殊一点

//      now.getMonth().compareTo() 月份之间比较 相同则为0
        Month month = LocalDate.now().getMonth();
        Month month1 = LocalDate.of(2023, 6, 1).getMonth();
        System.out.println(month.compareTo(month1));

6. 将一个日期字符串解析成日期对象

String dateStr = "2022-12-03";
LocalDate parse = LocalDate.parse(dateStr);
System.out.println(parse);


String dateStr2 = "2022年12月03日";
//按照指定格式来解析
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
LocalDate parse2 = LocalDate.parse(dateStr2, formatter); //
System.out.println(parse2);

System.out.println("======================");
String dateStr3 = "2021年10月05日 14点20分30秒";
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
LocalDateTime parse1 = LocalDateTime.parse(dateStr3, formatter2);
System.out.println(parse1);

7. 添加时间 plus

LocalDateTime ldt =LocalDateTime.now();
LocalDateTime localDateTime = ldt.plusYears(1);
LocalDateTime localDateTime1 = ldt.plusMonths(3);
LocalDateTime localDateTime2=ldt.plusHours(10);
LocalDateTime localDateTime2 = ldt.minusYears(8);

8. 计算时间间隔

  • Duration : 用于计算两个“时间”间隔的类

  • Period : 用于计算两个“日期”间隔的类


    //Duration:用于计算两个"时间”间隔的类
    Duration betweenNowAnd = Duration.between(preious, end);
    //long seconds = between.getSeconds(); //间隔的秒值
    long l = betweenNowAnd.toMillis();
    System.out.println("耗时:" + l + "毫秒");

    LocalDate birthday = LocalDate.of(2000, 3, 20);
    LocalDate nowday = LocalDate.now();
    //Period:用于计算两个“日期”间隔的类
    Period between = Period.between(birthday, nowday);
    int years = between.getYears();
    int months = between.getMonths();
    int days = between.getDays();
    System.out.println(years);
    System.out.println(months);
    System.out.println(days);
  1. 设定时区
//创建日期对象
LocalDateTime now = LocalDateTime.now();
//获取不同国家的日期时间根据各个地区的时区ID名创建对象
ZoneId timeID = ZoneId.of("Asia/Shanghai");
//根据时区ID获取带有时区的日期时间对象
ZonedDateTime time = now.atZone(timeID);
System.out.println(time);
//方式2 通过时区ID 获取日期对象
LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(now2);

小结

LocalDate/LocalDateTime都是不可变且线程安全的,位于java.time包中,可以为时区提供更好的支持,加上DateTimeFormatter之后日期的解析及格式化也更加得心应手。

Supongo que te gusta

Origin juejin.im/post/7235458133505015869
Recomendado
Clasificación