Java常用类-JDK8中之前日期时间API与JDK8中新日期时间API

JDK8中之前日期时间API

1.java.lang.System类

System类提供的 public static long currentTimeMillis
用来返回当前时间与 1970 年 1 月 1 日 0 时 0 分 0 秒之间以毫秒为单位的时间差。
此方法适于计算时间差。
long time = System.currentTimeMillis();
System.out.println(time);
称为时间戳

2.java.util.Date 类

表示特定的瞬间,精确到毫秒

  • 构造器
    • Date 使用无参构造 器 创建 的对象可以获取本地当前时间。
      Date date1 = new Date();
      System.out.println(date1.toString());

    • Date(long date) 创建指定毫秒数的Date对象

  • 常用方法
    • getTime 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
      System.out.println(date1.getTime());
    • toString 把此 Date 对象转换为以下形式的 String dow mon ddhh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue,Wed, Thu, Fri, Sat) zzz 是时间标准 。
    • 其它很多方法都过时了。

创建java.sql.Date对象

java.sql.Date date3 = new java.sql.Date(35235325345L);
System.out.println(date3);
如何将java.util.Date对象转换为java.sql.Date对象
  • 情况一:
Date date4 = new java.sql.Date(2343243242323L);
java.sql.Date date5 = (java.sql.Date) date4;
  • 情况二:
Date date6 = new Date();
java.sql.Date date7 = new java.sql.Date(date6.getTime());

3. java.text.SimpleDateFormat类

java.text.SimpleDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体 类。
它允许 进行 格式化:日期  文本 、 解析:文本  日期

SimpleDateFormat的使用:SimpleDateFormat对日期Date类的格式化和解析

  1. 两个操作:
  • 格式化
    日期 —>字符串
	SimpleDateFormat sdf = new SimpleDateFormat();
	Date date = new Date();
	System.out.println(date);
	
	String format = sdf.format(date);
	System.out.println(format);
  • 解析
    格式化的逆过程,字符串 —> 日期
    String str = "19-12-18 上午11:43";
    Date date1 = sdf.parse(str);
    System.out.println(date1);
  1. SimpleDateFormat的实例化
  • 实例化SimpleDateFormat:使用默认的构造器
    SimpleDateFormat sdf = new SimpleDateFormat();
  • 按照指定的方式格式化和解析:调用带参的构造器
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		//格式化
        String format1 = sdf1.format(date);
        System.out.println(format1);//2019-02-18 11:48:27
        //解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),否则,抛异常
        Date date2 = sdf1.parse("2020-02-18 11:48:27");
        System.out.println(date2);



4.java.util.Calendar 日历类

Calendar 是一个抽象基类,主用用于完成日期字段之间相互操作的功能。

  1. 实例化
    方式一:创建其子类(GregorianCalendar)的对象(调用构造器)
    方式二:调用其静态方法getInstance()
    Calendar calendar = Calendar.getInstance();
  2. 常用方法
		//get()
        int days = calendar.get(Calendar.DAY_OF_MONTH);//本月第多少天
        System.out.println(days);
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//本月第多少年

        //set()
        //calendar可变性
        calendar.set(Calendar.DAY_OF_MONTH,22);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

        //add()
        calendar.add(Calendar.DAY_OF_MONTH,-3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

        //getTime():日历类---> Date
        Date date = calendar.getTime();
        System.out.println(date);

        //setTime():Date ---> 日历类
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

JDK8中新日期时间API

JDK 1.0 中包含了一个 java.util.Date 类,但是它的大多数方法已经在 JDK 1.1 引入 Calendar 类之后被弃用了。而 Calendar 并不比 Date 好多少。它们面临的问题是:
可变性:像日期和时间这样的类应该是不可变的。
偏移性:Date 中的年份是从 1900 开始的,而月份都从 0 开始。
格式化:格式化只对Date 有用, Calendar 则不行。
此外,它们也不是线程安全的;不能处理闰秒等。

总结:对日期和时间的操作一直是Java 程序员最痛苦的地方之一。

Java 8 吸收了 Joda Time 的精华,以一个新的开始为 Java 创建优秀的 API 。
新的 java.time 中包含了所有关于 本地日期( LocalDate )本地时间
( LocalTime )
本地日期时间( LocalDateTime )时区 ZonedDateTime
和持续时间( Duration )的类
。历史悠久的 Date 类新增了 toInstant() 方法,
用于把 Date 转换成新的表示形式。这些新增的本地化时间日期 API 大大简
化了日期时间和本地化的管理。

在这里插入图片描述
说明:大多数开发者只会用到基础包和
format 包,也可能会用到 temporal 包。因此,尽
管有 68 个新的公开类型,大多数开发者,大概将只会用到其中的三分之一。

LocalDate 、 LocalTime 、 LocalDateTime

LocalDate 、 LocalTime 、 LocalDateTime 类是其中较重要的几个类,它们的 实例
是 不可变的对象 ,分别表示使用 ISO 8601 日历系统的日期、时间、日期和时间。
它们提供了简单 的本地日期 或时间,并不包含当前的时间 信息,也 不包含与时区
相关的信息 。

  • LocalDate 代表 IOS 格式( yyyy MM dd )的日期 可以存储 生日、纪念日等日期。
  • LocalTime 表示一个时间,而不是 日期 。
  • LocalDateTime 是用来表示日期和时间的,这是一个最常用的类之一
  1. LocalDate、LocalTime、LocalDateTime 的使用
    说明:
    1. LocalDateTime相较于LocalDate、LocalTime,使用频率要高
    2. 类似于Calendar
方法描述
now() / * now(ZoneId zone)静态方法,根据当前时间创建对象/指定时区的对象
of()静态方法,根据指定日期/时间创建对象
getDayOfMonth()/getDayOfYear()获得月份天数(1-31) /获得年份天数(1-366)
getDayOfWeek()获得星期几(返回一个 DayOfWeek 枚举值)
getMonth()获得月份, 返回一个 Month 枚举值
getMonthValue() / getYear()获得月份(1-12) /获得年份
getHour()/getMinute()/getSecond()获得当前对象对应的小时、分钟、秒
withDayOfMonth()/withDayOfYear()/withMonth()/withYear()将月份天数、年份天数、月份、年份修改为指定的值并返回新的对象
plusDays(), plusWeeks(),plusMonths(), plusYears(),plusHours()向当前对象添加几天、几周、几个月、几年、几小时
minusMonths() / minusWeeks()/minusDays()/minusYears()/minusHours()从当前对象减去几月、几周、几天、几年、几小时
public void test1(){
        //now():获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        //of():设置指定的年、月、日、时、分、秒。没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
        System.out.println(localDateTime1);

        //getXxx():获取相关的属性
        System.out.println(localDateTime.getDayOfMonth());
        System.out.println(localDateTime.getDayOfWeek());
        System.out.println(localDateTime.getMonth());
        System.out.println(localDateTime.getMonthValue());
        System.out.println(localDateTime.getMinute());
       
        //withXxx():设置相关的属性   (体现不可变性)
        LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);
        System.out.println(localDate1);
        LocalDateTime localDateTime2 = localDateTime.withHour(4);
        System.out.println(localDateTime);
        System.out.println(localDateTime2);

        //plusXxx/minusXxx(体现不可变性)
        LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);
        LocalDateTime localDateTime4 = localDateTime.minusDays(6);
        System.out.println(localDateTime);
        System.out.println(localDateTime4);
    }

瞬时: Instant

Instant :时间线上的一个瞬时点。 这可能被用来记录应用程序中的事件时间戳 。

在处理时间和日期的时候,我们通常会想到年,月,日,时,分,秒。然而,这只是时间的一个模型,是面向人类的。第二种通用模型是面向机器的,或者说是连续的。在此模型中,时间线中的一个点表示为一个很大的数,这有利于计算机处理。在UNIX中,这个数从1970年开始,以秒为的单位;同样的,在Java中,也是从1970年开始,但以毫秒为单位。

java.time包通过值类型Instant提供机器视图,不提供处理人类意义上的时间单位。Instant表示时间线上的一点,而不需要任何上下文信息,例如,时区。概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC)开始的秒数。因为java.time包是基于纳秒计算的,所以Instant的精度可以达到纳秒级。
● (1 ns = 10-9 s) 1秒 = 1000毫秒 =106微秒=109纳秒

Instant的使用与方法

方法描述
now()静态方法返回默认 UTC 时区的 Instant 类的对象
ofEpochMilli (long静态方法,返回在1970-01-01 00:00:00 基础上加上指定毫秒数之后的 Instant 类的对象
atOffset(ZoneOffset offset)结合即时的偏移来创建一个OffsetDateTime
toEpochMilli()返回1970-01-01 00:00:00 到当前时间的毫秒数 即为时间戳

时间戳是指格林威治时间1970 年 01 月 01 日 00 时 00 分 00 秒(北京时间 1970 年 01 月 01日 08 时 00 分 00 秒) 起至现在的总秒数。

public void test2(){
        //now():获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);//2019-02-18T07:29:41.719Z

        //添加时间的偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2019-02-18T15:32:50.611+08:00

        //toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数  ---> Date类的getTime()
        long milli = instant.toEpochMilli();
        System.out.println(milli);

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例  -->Date(long millis)
        Instant instant1 = Instant.ofEpochMilli(1550475314878L);
        System.out.println(instant1);
    }

DateTimeFormatter:格式化与解析日期 或 时间

java.time.format.DateTimeFormatter类:该类提供了三种格式化方法:

  1. 方式一:预定义的标准格式。如:
    ISO_LOCAL_DATE_TIME;
    ISO_LOCAL_DATE;
    ISO_LOCAL_TIME
   DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
   //格式化:日期-->字符串
   LocalDateTime localDateTime = LocalDateTime.now();
   String str1 = formatter.format(localDateTime);
   System.out.println(localDateTime);
   System.out.println(str1);//2021-08-22T16:31:15.455

   //解析:字符串 -->日期
   TemporalAccessor parse = formatter.parse("2021-08-22T16:31:15.455");
   System.out.println(parse);
  1. 方式二 本地化相关的格式。如:ofLocalizedDateTime()
    FormatStyle.LONG    / FormatStyle.MEDIUM    / FormatStyle.SHORT :适用于LocalDateTime
	DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
    //格式化
    String str2 = formatter1.format(localDateTime);
    System.out.println(str2);//2019年2月18日 下午03时47分16秒


//      本地化相关的格式。如:ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
    DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
    //格式化
    String str3 = formatter2.format(LocalDate.now());
    System.out.println(str3);//2019-2-18

重点 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)

  	 DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
     //格式化
     String str4 = formatter3.format(LocalDateTime.now());
     System.out.println(str4);//2019-02-18 03:52:09

     //解析
     TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09");
     System.out.println(accessor);

方法

ofPattern(Stringpattern)静态方法静态方法返回一个指定字符串格式的DateTimeFormatter
format(TemporalAccessort)格式化一个日期、 时间 返回字符串parse(CharSequence
parse(CharSequencetext)将指定格式的字符序列解析为一个日期、 时间

其他API

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

与 传统日期处理的 转换

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDK 8 之前Java 时间类主要有两个:`java.util.Date` 和 `java.util.Calendar`。 `java.util.Date` 类是用来表示日期时间的类。它包含了一些常用的方法,比如获取当前时间、设置时间、比较时间等。然而,`java.util.Date` 类有一些问题,比如它的设计不够好,不支持时区、线程安全性差等。 `java.util.Calendar` 类是一个抽象类,用于处理日期时间的各种操作。它提供了许多方法来获取和设置年、月、日、时、分、秒等信息,并且支持时区设置。使用 `java.util.Calendar` 类可以进行日期的加减运算、格式化输出等操作。 下面是一个简单的示例代码,演示了如何使用 `java.util.Date` 和 `java.util.Calendar` 类: ```java import java.util.Date; import java.util.Calendar; public class Main { public static void main(String[] args) { // 使用 java.util.Date 类 Date date = new Date(); System.out.println("当前时间:" + date); // 使用 java.util.Calendar 类 Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 注意月份是从 0 开始的,所以要加 1 int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); System.out.println("当前时间:" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second); } } ``` 总的来说,JDK 8 之前时间类使用起来比较繁琐,并且存在一些问题。在 JDK 8 之后,引入了日期时间 API(即 `java.time` 包),提供了更好的时间处理方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值