java8時間

時間api遺留問題

Date的不合理之處

在這裏插入圖片描述
在這裏插入圖片描述

Date date = new Date(114, 2, 18);
System.out.println(date); //Tue Mar 18 00:00:00 CST 2014

是2014年,這本書已經是5年前寫的了,感覺自己已經out了
看源碼可知這個方法已經過時了
它的年是從1900年開始
月又是從0開始
日是從1開始
所以很不友好
還有就是date 就是date 不應該有時間 time
java.util.Date#Date(int, int, int)

   /**
     * Allocates a <code>Date</code> object and initializes it so that
     * it represents midnight, local time, at the beginning of the day
     * specified by the <code>year</code>, <code>month</code>, and
     * <code>date</code> arguments.
     *
     * @param   year    the year minus 1900.
     * @param   month   the month between 0-11.
     * @param   date    the day of the month between 1-31.
     * @see     java.util.Calendar
     * @deprecated As of JDK version 1.1,
     * replaced by <code>Calendar.set(year + 1900, month, date)</code>
     * or <code>GregorianCalendar(year + 1900, month, date)</code>.
     */
    @Deprecated
    public Date(int year, int month, int date) {
        this(year, month, date, 0, 0, 0);
    }

SimpleDateFormat的多線程異常

還有一個問題 SimpleDateFormat的多線程操作


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date parse = sdf.parse("20160505");
        System.out.println(parse); //Thu May 05 00:00:00 CST 2016

這個在多線程下會有問題

    public static void main(String[] args) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                for (int x = 0; x < 100; x++) {
                    Date parseDate = null;
                    try {
                        parseDate = sdf.parse("20160505");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    System.out.println(parseDate);
                }
            }).start();
        }
    }

在這裏插入圖片描述
在這裏插入圖片描述
如果要用SimpleDateFormat 一般會對他 進行一個加鎖的處理

LocalDate

 private static void testLocalDate() {
        /**
         * LocalDate 用於替換date
         * @implSpec
         * This class is immutable and thread-safe.
         * @since 1.8.
         *
         * 它是線程安全的
         * 它只包含日期沒有時間
         */
        LocalDate localDate = LocalDate.of(2019, 5, 26);
        System.out.println(localDate.getYear()); //2019
        System.out.println(localDate.getMonth()); //MAY
        System.out.println(localDate.getMonthValue());//5
        System.out.println(localDate.getDayOfYear());//146
        System.out.println(localDate.getDayOfMonth());//26
        System.out.println(localDate.getDayOfWeek());//SUNDAY
        //上面的和我本地時間都是一一對應的

        System.out.println(localDate);//2019-05-26

        LocalDate now = LocalDate.now();
        System.out.println(now); //2019-05-26

        /**
         * ChronoField 枚舉
         * This is a final, immutable and thread-safe enum.
         * @since 1.8
         */

        int i = localDate.get(ChronoField.DAY_OF_MONTH);
        System.out.println(i); //26
    }

LocalTime

   private static void testLocalTime() {
        LocalTime time = LocalTime.now();
        System.out.println(time.getHour()); //21
        System.out.println(time.getMinute());//48
        System.out.println(time.getSecond());//1

        System.out.println(time); //21:49:03.978

    }

LocalDateTime

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

        LocalDateTime localDateTime = LocalDateTime.of(localDate, time);
        System.out.println(localDateTime.toString()); //2019-05-26T21:50:02.953
        
        LocalDateTime now = LocalDateTime.now(); 
        System.out.println(now);//2019-05-26T21:50:02.953
    }

Calendar

java.util.Calendar#Calendar()

    /**
     * Constructs a Calendar with the default time zone
     * and the default {@link java.util.Locale.Category#FORMAT FORMAT}
     * locale.
     * @see     TimeZone#getDefault
     */
    protected Calendar()
    {
        this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
        sharedZone = true;
    }

java.util.Calendar#getInstance()

 /**
     * Gets a calendar using the default time zone and locale. The
     * <code>Calendar</code> returned is based on the current time
     * in the default time zone with the default
     * {@link Locale.Category#FORMAT FORMAT} locale.
     *
     * @return a Calendar.
     */
    public static Calendar getInstance()
    {
        return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
    }

測試

     Calendar instance = Calendar.getInstance();
        System.out.println(instance.get(Calendar.YEAR)); //2019
        System.out.println(instance.get(Calendar.MONTH)); //4  實際當前月爲5月 ,可見Calendar月從0開始
        System.out.println(instance.get(Calendar.DATE));  //26
        System.out.println(instance.get(Calendar.DAY_OF_MONTH));//26
        System.out.println(instance.get(Calendar.DAY_OF_YEAR));//146
        System.out.println(instance.get(Calendar.DAY_OF_WEEK));//1  星期天是一週的第一天
        System.out.println(instance.get(Calendar.MONDAY));//4   5月1號 星期三 一週的第4天

        Date date = instance.getTime();// Calendar 轉換爲date
        instance.setTime(date);//date -> Calendar     
        System.out.println(instance.getTime()); //Sun May 26 22:02:50 CST 2019

Instant

  • An instantaneous point on the time-line.
  • This class models a single instantaneous point on the time-line.
  • This might be used to record event time-stamps in the application.

時間點的意思

   private static void testInstant() throws InterruptedException {
        Instant start = Instant.now();
        //System.out.println(start.get(ChronoField.YEAR)); //Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:  Unsupported field: Year
        Thread.sleep(1000L);
        System.out.println(start); //2019-05-26T14:13:33.732Z
        

        Instant end = Instant.now();
        Duration duration = Duration.between(start, end);
        System.out.println(duration.toMillis()); //1082
        System.out.println(duration.toNanos()); //1082000000
        System.out.println(duration.toMinutes());//0

        //類比currentTimeMillis
        long l = System.currentTimeMillis();
    }
    }

銫se

銫鐘一種精密的計時器具。日常生活中使用的時間準到1分鐘也就夠了。但在近代的社會生產、科學研究和國防建設等部門,對時間的要求就高得多。它們要求時間要準到千分之一秒,甚至百萬分之一秒。爲了適應這些高精度的要求,人們製造出了一系列精密的計時器具,銫鐘就是其中的一種。銫鐘又叫“銫原子鐘”。它利用銫原子內部的電子在兩個能級間跳躍時輻射出來的電磁波作爲標準,去控制校準電子振盪器,進而控制鐘的走動。這種鐘的穩定程度很高,最好的銫原子鐘達到500萬年才相差 1 秒。國際上, 普遍採用銫原子鐘的躍遷頻率作爲時間頻率的標準,廣泛使用在天文、大地測量和國防建設等各個領域中。

時間這方面的科學研究大家自行bing

Duration

This class models a quantity or amount of time in terms of seconds and nanoseconds.
時間段

    private static void testDuration() {
        LocalTime time = LocalTime.now();
        LocalTime beforeTime = time.minusHours(1); // Returns a copy of this {@code LocalTime} with the specified number of hours subtracted.
        Duration duration = Duration.between(time, beforeTime);
        System.out.println(duration.toHours()); //1
    }

Period

This class models a quantity or amount of time in terms of years, months and days.
時代 週期

   private static void testPeriod() {
        Period period = Period.between(LocalDate.of(2014, 1, 10), LocalDate.of(2016, 1, 10));
        System.out.println(period.getMonths());//0
        System.out.println(period.getDays());//0
        System.out.println(period.getYears());//2
    }

String format(DateTimeFormatter formatter) 時間格式化成字符串

    private static void testDateFormat() {
        LocalDate localDate = LocalDate.now();
        String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(format1); //20190526
       // String format2 = localDate.format(DateTimeFormatter.ISO_LOCAL_TIME);
        //System.out.println(format2);
        //報錯java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay

        //自定義時間格式字符串
        DateTimeFormatter mySelfFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = localDate.format(mySelfFormatter);
        System.out.println(format); //2019-05-26

    }

LocalDate parse(CharSequence text, DateTimeFormatter formatter) 字符串轉換時間

    private static void testDateParse() {
        String date1 = "20161113";
        LocalDate localDate = LocalDate.parse(date1, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(localDate); //2016-11-13

        //自定義格式
        DateTimeFormatter mySelfFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String date2 = "2016-11-13";
        LocalDate localDate2 = LocalDate.parse(date2, mySelfFormatter);
        System.out.println(localDate2); //2016-11-13

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章