java8时间

文章目录

    • 时间api遗留问题
      • Date的不合理之处
      • SimpleDateFormat的多线程异常
    • LocalDate
    • LocalTime
    • LocalDateTime
    • Calendar
    • Instant
    • Duration
    • Period
    • String format(DateTimeFormatter formatter) 时间格式化成字符串
    • LocalDate parse(CharSequence text, DateTimeFormatter formatter) 字符串转换时间

时间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 Date object and initializes it so that
     * it represents midnight, local time, at the beginning of the day
     * specified by the year, month, and
     * date 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 Calendar.set(year + 1900, month, date)
     * or GregorianCalendar(year + 1900, month, date).
     */
    @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
     * Calendar 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

    }

你可能感兴趣的:(jdk8)