百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

一张机,织梭光景去如飞:JDK时间变迁

yuyutoo 2025-04-24 10:16 35 浏览 0 评论

夫天地者,万物之逆旅;光阴者,百代之过客。

背景

阿里《java开发手册》中提到:

说明:如果是 JDK8 的应用,可以使用 Instant 代替 Date,LocalDateTime 代替 Calendar,
DateTimeFormatter 代替 SimpleDateFormat,官方给出的解释:simple beautiful strong immutable
thread-safe。

JDK8中的时间函数与以前的版本有个根本性的改变,完全废弃了之前关于时间函数的设计。今天就聊聊这个jdk时间的设计变迁过程。这个变迁大致分为三个过程:最初的Date设计(JDK1.0),Date设计的补丁版Calendar(JDK1.1),重新设计(JDK1.8).

Date出世

先从一个实例开始吧!

  public static void dateTest() {
    Date date=new Date();
    System.out.println(date.getYear()+" " + date.getMonth()+ " "+date.getDay());
  }

打印出的结果是:

122 6 5

注意:当前的日期是 2022-07-01

是不是很惊喜?是不是很意外?

翻看Date的说明文档,让我们来看看原因:

    /**
     * Returns a value that is the result of subtracting 1900 from the
     * year that contains or begins with the instant in time represented
     * by this <code>Date</code> object, as interpreted in the local
     * time zone.
     *
     * @return  the year represented by this date, minus 1900.
     * @see     java.util.Calendar
     * @deprecated As of JDK version 1.1,
     * replaced by <code>Calendar.get(Calendar.YEAR) - 1900</code>.
     */
    @Deprecated
    public int getYear() {
        return normalize().getYear() - 1900;
    }
    
       /**
     * Returns a number representing the month that contains or begins
     * with the instant in time represented by this <tt>Date</tt> object.
     * The value returned is between <code>0</code> and <code>11</code>,
     * with the value <code>0</code> representing January.
     *
     * @return  the month represented by this date.
     * @see     java.util.Calendar
     * @deprecated As of JDK version 1.1,
     * replaced by <code>Calendar.get(Calendar.MONTH)</code>.
     */
    @Deprecated
    public int getMonth() {
        return normalize().getMonth() - 1; // adjust 1-based to 0-based
    } 
    
    /**
     * Returns the day of the week represented by this date. The
     * returned value (<tt>0</tt> = Sunday, <tt>1</tt> = Monday,
     * <tt>2</tt> = Tuesday, <tt>3</tt> = Wednesday, <tt>4</tt> =
     * Thursday, <tt>5</tt> = Friday, <tt>6</tt> = Saturday)
     * represents the day of the week that contains or begins with
     * the instant in time represented by this <tt>Date</tt> object,
     * as interpreted in the local time zone.
     *
     * @return  the day of the week represented by this date.
     * @see     java.util.Calendar
     * @deprecated As of JDK version 1.1,
     * replaced by <code>Calendar.get(Calendar.DAY_OF_WEEK)</code>.
     */
    @Deprecated
    public int getDay() {
        return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;
    }

自此,明白了:年=2022-1900=122,月=6+1=7,日=周五。

Calendar打补丁

在 1.1 版中,Calendar 类被添加到了 Java 平台中,以矫正 Date 的缺点,由此大部分的 Date 方法就都被弃用了。遗憾的是,这么做只能使情况更糟。

  public static void calendarTest() {
      Calendar cal = Calendar.getInstance();
      cal.set(2018, 12, 31); // Year, Month, Day
      System.out.print(cal.get(Calendar.YEAR) + " "+cal.get(Calendar.MONTH) + " "+cal.get(Calendar.DAY_OF_MONTH));
  }

结果显示:

2019 0 31

从上面的理解中,月份是从 0 开始的即 0~11 代表 1 月…12 月

接着 day又是从 1 开始的,为什么同一个方法设计的如此怪异?

JDK1.8:破而后立

Java 8的日期和时间类包含Instant、LocalDate、LocalTime、LocalDateTime、Duration以及Period,这些类都包含在java.time包中。

(1)Instant

在 JDK8 中,针对统计时间 等场景,推荐使用 Instant 类来代替Date。如果想获取更加精确的纳秒级时间值,使用 System.nanoTime 的方式。其使用实例如下:

  public static void instantTest() {
    Instant instant=Instant.now();
    System.out.println(instant.getEpochSecond());
    //System.out.println(System.currentTimeMillis());
    System.out.println(instant.getNano());
  }

显示结果:

1656896732
236000000

(2)使用LocalDate、LocalTime、LocalDateTime来替换Calendar

    public static void localDateTimeTest() {
    LocalDate date=LocalDate.of(2022, 7, 4);
    System.out.println(date.getYear()+" "+date.getMonthValue()+" "+date.getDayOfMonth());
    
    LocalTime time=LocalTime.of(10, 05, 30);
    System.out.println(time.getHour()+" "+time.getMinute()+" "+ time.getSecond());
    
    LocalDateTime dtime=LocalDateTime.of(2022, 7, 4, 10, 5,30);
    System.out.println(dtime.getYear()+" "+dtime.getMonthValue()+" "+dtime.getDayOfMonth()+
        " "+dtime.getHour()+" "+dtime.getMinute());
    
    }

结果显示:

2022 7 4
10 5 30
2022 7 4 10 5

(3)Duration

表示一个时间段,所以Duration类中不包含now()静态方法。可以通过Duration.between()方法创建Duration对象

    public static void durationTest() {
      LocalDateTime from = LocalDateTime.of(2022, 7, 1, 10, 7, 0);    
      LocalDateTime to = LocalDateTime.of(2022, 7, 4, 10, 7, 0);    
      Duration d = Duration.between(from, to);
      System.out.println(d.toDays()+" "+ d.toHours()+" "+d.toMinutes() +" "+d.getSeconds()+" "+ d.getNano());
    }

结果显示:

3 72 4320 259200 0

(4)Period

Period在概念上和Duration类似,区别在于Period是以年月日来衡量一个时间段,比如2年3个月6天

  public static void periodTest() {
    Period p = Period.between(
                LocalDate.of(2022, 7, 1),
                LocalDate.of(2022, 7, 4));
    System.out.println(p.getYears()+" "+ p.getMonths()+" "+p.getDays());
  }

结果显示“

0 0 3

时间转换

因历史原因,jdk1.8的时间api有时候还是需要转换为Date。

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
 
public class DateUtils {
   //LocalDate 转Date 
    public static Date asDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }
 //LocalDateTime 转Date 
    public static Date asDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
 //Date 转LocalDate 
    public static LocalDate asLocalDate(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
    }
 // Date 转LocalDateTime
    public static LocalDateTime asLocalDateTime(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}

小结

JDK1.8的时间进行重新设计,使用Instant、LocalDate、LocalTime、LocalDateTime、Duration以及Period等来替代Date、Calendar设计。使用时要注意:

(1)不要在程序中写死一年为 365 天,避免在公历闰年时出现日期转换错误或程序逻辑错误。使用LocalDate.now().lengthOfYear()获取今年的天数。

(2)不允许在程序任何地方中使用:1)java.sql.Date 2)java.sql.Time 3)java.sql.Timestamp。

(3)DateTimeFormatter 代替 SimpleDateFormat.前者是线程安全的,后者线程不安全。

相关推荐

《保卫萝卜2》安卓版大更新 壕礼助阵世界杯

《保卫萝卜2:极地冒险》本周不仅迎来了安卓版本的重大更新,同时将于7月4日本周五,带来“保卫萝卜2”安卓版本世界杯主题活动的火热开启,游戏更新与活动两不误。一定有玩家会问,激萌塔防到底进行了哪些更新?...

儿童手工折纸:胡萝卜,和孩子一起边玩边学carrot

1、准备两张正方形纸,一橙一绿,对折出折痕。2、橙色沿其中一条对角线如图折两三角形。3、把上面三角折平,如图。4、绿色纸折成三角形。5、再折成更小的三角形。6、再折三分之一如图。7、打开折纸,压平中间...

《饥荒》食物代码有哪些(饥荒最新版代码总汇食物篇)

饥荒游戏中,玩家们需要获取各种素材与食物,进行生存。玩家们在游戏中,进入游戏后按“~”键调出控制台使用代码,可以直接获得素材。比如胡萝卜的代码是carrot,玉米的代码是corn,南瓜的代码是pump...

Skyscanner:帮你找到最便宜机票 订票不求人

你喜欢旅行吗?在合适的时间、合适的目的地,来一场说走就走的旅行?机票就是关键!Skyscanner这款免费的手机应用,在几秒钟内比较全球600多家航空公司的航班安排、价格和时刻表,帮你节省金钱和时间。...

小猪佩奇第二季50(小猪佩奇第二季英文版免费观看)

Sleepover过夜Itisnighttime.现在是晚上。...

我在民政局工作的那些事儿(二)(我在民政局上班)

时间到了1997年的秋天,经过一年多的学习和实践,我在处理结婚和离婚的事情更加的娴熟,也获得了领导的器重,所以我在处理平时的工作时也能得心应手。这一天我正在离婚处和同事闲聊,因为离婚处几天也遇不到人,...

夏天来了就你还没瘦?教你不节食13天瘦10斤的哥本哈根减肥法……

好看的人都关注江苏气象啦夏天很快就要来了你是否和苏苏一样身上的肉肉还没做好准备?真是一个悲伤的故事……下面这个哥本哈根减肥法苏苏的同事亲测有效不节食不运动不反弹大家快来一起试试看吧~DAY1...

Pursuing global modernization for peaceful development, mutually beneficial cooperation, prosperity for all

AlocalworkeroperatesequipmentintheChina-EgyptTEDASuezEconomicandTradeCooperationZonei...

Centuries-old tea road regains glory as Belt and Road cooperation deepens

FUZHOU/ST.PETERSBURG,Oct.2(Xinhua)--NestledinthepicturesqueWuyiMountainsinsoutheastChi...

15 THE NUTCRACKERS OF NUTCRACKER LODGE (CONTINUED)胡桃夹子小屋里的胡桃夹子(续篇)

...

AI模型部署:Triton Inference Server模型部署框架简介和快速实践

关键词:...

Ftrace function graph简介(flat function)

引言由于android开发的需要与systrace的普及,现在大家在进行性能与功耗分析时候,经常会用到systrace跟pefetto.而systrace就是基于内核的eventtracing来实...

JAVA历史版本(java各版本)

JAVA发展1.1996年1月23日JDK1.0Java虚拟机SunClassicVM,Applet,AWT2.1997年2月19日JDK1.1JAR文件格式,JDBC,JavaBea...

java 进化史1(java的进阶之路)

java从1996年1月第一个版本诞生,到2022年3月最新的java18,已经经历了27年,整整18个大的版本。很久之前有人就说java要被淘汰,但是java活到现在依然坚挺,不知道java还能活...

学习java第二天(java学完后能做什么)

#java知识#...

取消回复欢迎 发表评论: