Java 8 - 时间API

举报
小工匠 发表于 2021/09/09 23:33:17 2021/09/09
【摘要】 文章目录 Pre模拟SimpleDateFormate线程安全问题LocalDateLocalTimeLocalDateTimeInstantPeriodDurationformatparse ...


在这里插入图片描述

Pre

并发编程-12线程安全策略之常见的线程不安全类


模拟SimpleDateFormate线程安全问题

package com.artisan.java8.testDate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/3/5 0:22
 * @mark: show me the code , change the world
 */
public class DateInJava8 {


    public static void main(String[] args) throws ParseException, InterruptedException {

        Date date = new Date();
        System.out.println(date);


        /**
         *  模拟SimpleDateFormat 的线程安全问题
         *
         *  Exception in thread "Thread-30" java.lang.NumberFormatException: multiple points
         *
         *  Exception in thread "Thread-24" java.lang.NumberFormatException: For input string: "E.250214E4"
         *
         */
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");

        for (int i = 0; i < 100; i++) {
             new Thread(() -> {
                 for (int j = 0; j < 20; j++) {
                     try {
                         String format = sdf.format(date);
                         Date d = sdf.parse(format);
                         System.out.println(d);
                     } catch (ParseException e) {
                         e.printStackTrace();
                     }
                 }
             }).start();
        }


    }


}
    

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

在这里插入图片描述


LocalDate

https://nowjava.com/docs/java-api-11/java.base/java/time/LocalDate.html

LocalDate 是final修饰的不可变类 并且是线程安全的.

在这里插入图片描述

  • Java LocalDate is immutable class and hence thread safe.

  • LocalDate provides date output in the format of YYYY-MM-dd.
    在这里插入图片描述

  • The LocalDate class has no time or Timezone data. So LocalDate is suitable to represent dates such as Birthday, National Holiday etc.

  • LocalDate class implements Temporal, TemporalAdjuster, ChronoLocalDate and Serializable interfaces.

  • LocalDate is a final class, so we can’t extend it.

  • LocalDate is a value based class, so we should use equals() method for comparing if two LocalDate instances are equal or not.

 public static void testLocalDate(){
        LocalDate x = LocalDate.now(); // 日期  2021-03-05
        System.out.println(x);


        LocalDate lo = LocalDate.of(2021,3,5);
        System.out.println(lo.getYear()); // 年  2021
        System.out.println(lo.getMonth()); // 月 MARCH
        System.out.println(lo.getDayOfMonth()); // 日 5

        System.out.println(lo.getDayOfYear()); // 一年中的第几天
        System.out.println(lo.getDayOfMonth());// 一个月中的第几天
        System.out.println(lo.getDayOfWeek());// 礼拜几


        System.out.println(lo.get(ChronoField.DAY_OF_MONTH));

    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

LocalTime

  • LocalTime provides time without any time zone information. It is very much similar to observing the time from a wall clock which just shown the time and not the time zone information.

  • The assumption from this API is that all the calendar system uses the same way of representing the time.

  • It is a value-based class, so use of reference equality (==), identity hash code or synchronization on instances of LocalTime may have - unexpected results and is highly advised to be avoided. The equals method should be used for comparisons.

  • The LocalTime class is immutable that mean any operation on the object would result in a new instance of LocalTime reference.

private static void testLocalTime() {
        LocalTime time = LocalTime.now();
        System.out.println(time.getHour());
        System.out.println(time.getMinute());
        System.out.println(time.getSecond());
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

LocalDateTime

  • Java LocalDateTime is an immutable class, so it’s thread safe and suitable to use in multithreaded environment.

  • LocalDateTime provides date and time output in the format of YYYY-MM-DD-hh-mm-ss.zzz, extendable to nanosecond precision. So we can store “2017-11-10 21:30:45.123456789” in LocalDateTime object.
    在这里插入图片描述

  • Just like the LocalDate class, LocalDateTime has no time zone data. We can use LocalDateTime instance for general purpose date and time information.

  • LocalDateTime class implements Comparable, ChronoLocalDateTime, Temporal, TemporalAdjuster, TermporalAccessor and Serializable interfaces.

  • LocalDateTime is a final class, so we can’t extend it.

  • LocalDateTime is a value based class, so we should use equals() method to check if two instances of LocalDateTime are equal or not.

  • LocalDateTime class is a synergistic ‘combination’ of LocalDate and LocalTime with the contatenated format as shown in the figure above.

    private static void testLocalDateTime() {
        LocalDate localDate = LocalDate.now();
        LocalTime time = LocalTime.now();

        LocalDateTime localDateTime = LocalDateTime.of(localDate, time);
        System.out.println(localDateTime.toString());
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Instant

    private static void testInstant() throws InterruptedException {
        Instant start = Instant.now();
        Thread.sleep(1000L);
        Instant end = Instant.now();
        Duration duration = Duration.between(start, end);
        System.out.println(duration.toMillis());
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Period

    private static void testPeriod() {
        Period period = Period.between(LocalDate.of(2020, 5, 10),LocalDate.of(2021, 3, 4));
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Duration


 
   private static void testDuration() {
        LocalTime time = LocalTime.now();
        System.out.println(time);
        LocalTime beforeTime = time.minusHours(2);
        System.out.println(beforeTime);
        Duration duration = Duration.between(beforeTime,time );
        System.out.println(duration.toHours());
    }
 

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

format

    private static void testDateFormat() {
        LocalDate localDate = LocalDate.now();
        String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(format1);

        DateTimeFormatter mySelfFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = localDate.format(mySelfFormatter);
        System.out.println(format);
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

parse

  private static void testDateParse() {
        String date1 = "20210305";
        LocalDate localDate = LocalDate.parse(date1, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(localDate);
       

        DateTimeFormatter mySelfFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String date2 = "2021-03-05";
        LocalDate localDate2 = LocalDate.parse(date2, mySelfFormatter);
        System.out.println(localDate2);
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

文章来源: artisan.blog.csdn.net,作者:小小工匠,版权归原作者所有,如需转载,请联系作者。

原文链接:artisan.blog.csdn.net/article/details/114394036

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。