Java常用类04:Java中日期时间的API

JDK8之前日期时间的API

1. System类中获取时间戳的方法

System类中的currentTimeMillis()方法:返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差,称为时间戳。


public class SystemTime {

    @Test
    public void test1() {
        long time = System.currentTimeMillis();
        System.out.println(time); //1658150545728
    }
}

2. java.util.Date类和java.sql.Date类

java.util.Date类

  1. 两个构造器的使用
    构造器1:Date() 创建一个对应当前时间的Date对象
    构造器2:Date(long date) 创建指定毫秒数的Date对象
  2. 两个方法的使用
    toString():显示当前的年、月、日、时、分、秒
    getTime():获取当前Date对象对应的毫秒数(时间戳)

java.sql.Date类对应着数据库中的日期类型的变量
如何实例化
如何将java.util.Date对象转换为java.sql.Date对象


import java.util.Date;

public class DataTime {

    @Test
    public void test2() {
        //构造器1:Date()  创建一个对应当前时间的Date对象
        Date date1 = new Date();
        System.out.println(date1.toString()); //Mon Jul 18 23:22:01 KST 2022
        System.out.println(date1.getTime()); //1658154292336

        //构造器2:Date(long date)  创建指定毫秒数的Date对象
        Date date2 = new Date(1658154292336L);
        System.out.println(date2); //Mon Jul 18 23:24:52 KST 2022

        //创建java.sql.Date对象
        java.sql.Date date3 = new java.sql.Date(1658154292336L);
        System.out.println(date3); //2022-07-18

        //如何将java.util.Date对象转换为java.sql.Date对象
        //情况一:
        Date date4 = new java.sql.Date(1658154292336L);
        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类

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

  1. 两个操作:
    1.1 格式化:日期 --> 字符串
    1.2 解析:字符串 --> 日期(格式化的逆过程) 要求字符串必须符合SimpleDateFormat识别的格式(通过构造器参数体现),否则就会抛异常

  2. SimpleDateFormat的实例化

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatTest {

    @Test
    public void testSimpleDateFormat() throws ParseException {
        //实例化SimpleDateFormat:使用默认的构造器
        SimpleDateFormat sdf = new SimpleDateFormat();

        //格式化:日期 --> 字符串
        Date date = new Date();
        System.out.println(date); //Wed Jul 20 14:36:45 KST 2022

        String format = sdf.format(date);
        System.out.println(format); //22-7-20 下午2:36

        //解析:字符串 --> 日期
        String str = "22-08-04 上午8:00"; //默认格式
        Date date1 = sdf.parse(str);
        System.out.println(date1); //Thu Aug 04 08:00:00 KST 2022

        //实例化SimpleDateFormat:使用参数为指定格式的构造器(开发中主要使用的方式)
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format1 = sdf1.format(date);
        System.out.println(format1); //2022-07-20 02:36:45
        //解析
        Date date2 = sdf1.parse("2022-11-19 19:00:00");
        System.out.println(date2); //Sat Nov 19 19:00:00 KST 2022
    }
}

练习:将字符串"2020-09-08"转换为java.sql.Date

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatTest1 {

    @Test
    public void test() throws ParseException {
        String birth = "2020-09-08";

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf1.parse(birth);

        java.sql.Date birthDate = new java.sql.Date(date.getTime());
        System.out.println(birthDate); //2020-09-08  java.sql.Date类型的2020-09-08
    }
}

4. Calendar 日历类

Calendar 日历类(抽象类)的使用
Calendar是一个抽象基类,主要功能为完成日期字段之间的相互操作

获取Calendar实例的方法:
方式一:调用它的子类GregorianCalendar的构造器。
方式二:调用Calendar.getInstance()方法; (一般使用这个)

注意:
获取月份时:一月是0,二月是1,以此类推,12月是11
获取星期时:周日是1,周一是2,以此类推,周六是7

import org.junit.Test;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class CalendarTest {

    @Test
    public void testCalendar() {
        //1.实例化:调用Calendar.getInstance()方法
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getClass());  //class java.util.GregorianCalendar  实际还是调用子类

        //2.常用方法:
        // get()
        int days = calendar.get(Calendar.DAY_OF_MONTH); //这个月的第几天
        System.out.println(days); //21
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //202  这一年的第几天

        // set()
        calendar.set(Calendar.DAY_OF_MONTH, 22); //修改calendar对象本身的日期
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days); //22
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //203

        // add()
        calendar.add(Calendar.DAY_OF_MONTH, 3); //将calendar的日期加3,想要减去的话就是-3
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days); //25
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //206

        //getTime():Calendar日历类 --> Date类
        Date date = calendar.getTime();
        System.out.println(date); //Mon Jul 25 18:03:25 KST 2022

        //setTime():Date类 --> Calendar日历类
        Date date1 = new Date(); //当前时间
        calendar.setTime(date1); //转换为Calendar日历类
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days); //21
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //202
    }
}

JDK8中新日期时间的API

1. JDK8之前日期时间的API的不足
  • 可变性:像日期和时间这样的类应该是不可变的。
  • 偏移性:Date中的年份是从1900开始的,而月份都是从0开始的。
  • 格式化:格式化只对Date有用,Calendar则不行。
  • 此外,它们也不是线程安全的;不能处理闰秒等。

public void testDate() {
    //偏移性
    Date date = new Date(2020 - 1900, 9 - 1, 8);
    System.out.println(date); //Tue Sep 08 00:00:00 KST 2020
}

2. LocalDate、LocalTime、LocalDateTime的使用

说明:
  1. LocalDate、LocalTime、LocalDateTime类是较重要的几个类,它们的实例是不可变的对象,分别表示使用 ISO-8601 日历系统的日期、时间、日期和时间。
  2. 它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。
  3. LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储生日、纪念日等日期。
   LocalTime表示一个时间,而不是日期。
   LocalDateTime是用来表示日期和时间的,这是一个最常用的类之一
  4. 类似于Calendar。


public class NewDateTime {

    @Test
    public void test1() {
        //now():获取当前日期、时间、日期 + 时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate); //2022-07-23
        System.out.println(localTime); //01:18:31.915
        System.out.println(localDateTime); //2022-07-23T01:18:31.915

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

        //getXxx():获取相关的属性
        System.out.println(localDateTime.getDayOfMonth()); //23  这个月的第几天
        System.out.println(localDateTime.getDayOfWeek()); //SATURDAY  星期几
        System.out.println(localDateTime.getMonth()); //JULY  几月
        System.out.println(localDateTime.getMonthValue()); //7  几月(数字)
        System.out.println(localDateTime.getMinute()); //18  几分

        //withXxx():设置相关的属性  不可变性  原对象的值不变生成一个新的对象
        LocalDate localDate1 = localDate.withDayOfMonth(25); //设为这个月的第25天
        System.out.println(localDate); //2022-07-23  当前时间
        System.out.println(localDate1); //2022-07-25

        LocalDateTime localDateTime2 = localDateTime.withHour(6); //设为6点
        System.out.println(localDateTime); //2022-07-23T01:18:31.915 当前时间
        System.out.println(localDateTime2); //2022-07-23T06:18:31.915

        //addXxx():加  不可变性
        LocalDateTime localDateTime3 = localDateTime.plusMonths(3); //加上3个月
        System.out.println(localDateTime); //2022-07-23T01:18:31.915  当前时间
        System.out.println(localDateTime3); //2022-10-23T01:18:31.915

        //minusXxx():减  不可变性
        LocalDateTime localDateTime4 = localDateTime.minusDays(6); //减去6天
        System.out.println(localDateTime); //2022-07-23T01:18:31.915  当前时间
        System.out.println(localDateTime4); //2022-07-17T01:18:31.915

    }
}

3. Instant的使用
  • 时间线上的一个瞬时点。可能被用来记录应用程序中的时间时间戳。概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC)开始的毫秒数。
  • 类似于 java.util.Date类

public class InstantTest {

    @Test
    public void test2() {
        //now():获取UTC时间(世界标准时间)
        Instant instant = Instant.now();
        System.out.println(instant); //2022-07-22T16:48:50.950Z  UTC时间

        //atOffset(ZoneOffset.ofHours):添加时间偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime); //2022-07-23T00:57:06.161+08:00  北京时间  东八区  UTC+8

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

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例  --> Date(Long Millis)
        Instant instant1 = Instant.ofEpochMilli(1658509890786L);
        System.out.println(instant1); //2022-07-22T17:11:30.786Z
    }
}

4. DateTimeFormatter类(格式化与解析日期或时间)

DateTimeFormatter:格式化或解析日期、时间
类似于SimpleDateFormat
实例化方式:
1.预定义的标准格式:如 ISO_LOCAL_DATE_TIME、ISO_LOCAL_DATE; ISO_LOCAL_TIME
2.本地化相关的格式:如 ofLocalizedDateTime(FormatStyle.LONG)、ofLocalizedDate(FormatStyle.FULL)
3.自定义的格式:如 ofPattern(“yyyy-MM-dd hh:mm:ss E”) 重点 最常用!


public class DateTimeFormatterTest {

    @Test
    public void test3() {
        //1.预定义的标准格式:如 ISO_LOCAL_DATE_TIME、ISO_LOCAL_DATE、ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期 --> 字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str = formatter.format(localDateTime);
        System.out.println(localDateTime); //2022-07-23T18:00:36.459  LocalDateTime
        System.out.println(str); //2022-07-23T18:00:36.459  String
        //解析:字符串 --> 日期
        TemporalAccessor parse = formatter.parse("2022-07-23T17:11:53.297");
        System.out.println(parse); //{},ISO resolved to 2022-07-23T17:11:53.297

        //2.本地化相关的格式:
        //如 ofLocalizedDateTime(FormatStyle.LONG)
        //FormatStyle.LONG、FormatStyle.MEDIUM、FormatStyle.SHORT 适用于LocalDateTime的三种格式
        //FormatStyle.LONG
        DateTimeFormatter formatterLong = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        String str1 = formatterLong.format(localDateTime);
        System.out.println(str1); //2022年7月23日 下午06时00分36秒
        //FormatStyle.MEDIUM
        DateTimeFormatter formatterMedium = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
        String str2 = formatterMedium.format(localDateTime);
        System.out.println(str2); //2022-7-23 18:00:36

        //如 ofLocalizedDate(FormatStyle.FULL)
        //FormatStyle.FULL、FormatStyle.LONG、FormatStyle.MEDIUM、FormatStyle.SHORT 适用于LocalDate的三种格式
        //FormatStyle.FULL
        DateTimeFormatter formatterFull = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        String str4 = formatterFull.format(LocalDate.now()); //格式化
        System.out.println(str4); //2022年7月23日 星期六
        //FormatStyle.SHORT
        DateTimeFormatter formatterShort = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
        String str5 = formatterShort.format(LocalDate.now());
        System.out.println(str5); //22-7-23

        //3.自定义的格式:如 ofPattern("yyyy-MM-dd hh:mm:ss E")  重点  最常用!
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss E");
        //格式化
        String str6 = formatter1.format(LocalDateTime.now());
        System.out.println(str6); //2022-07-23 06:00:36 星期六
        //解析
        TemporalAccessor accessor = formatter1.parse("2022-07-23 05:52:09 星期六");
        System.out.println(accessor);
        //{MilliOfSecond=0, MicroOfSecond=0, SecondOfMinute=9, HourOfAmPm=5, NanoOfSecond=0, MinuteOfHour=52},ISO resolved to 2022-07-23
    }
}

4. 其它API

Zoneld:该类中包含了所有的时区信息。某一个时区的ID,如 Europe/Paris(欧洲/巴黎 东一区)。
ZonedDateTime:一个在ISO-8601日历系统时区的日期时间,如 2007-12-03T10:15:30+01:00 Europe/Paris。其中每个时区都对应着ID,地区ID都为"{区域}/{城市}"的格式。例如,Asia/Shanghai 等。
Clock:使用时区提供对当前即时、日期和时间的访问的时钟
Duration:持续时间。用于计算两个"时间"的间隔
Period:日期间隔。用于计算两个"日期"的间隔
TemporalAdjuster:时间校正器。有时我们可能需要获取例如:将日期调整到"下一个工作日"等操作。
TemporalAdjusters:该类通过静态方法 (firstDayOfXxx)()/lastDayOfXxx()/nextXxx())提供了大量的常用TemporalAdjuster的实现。

5. 与传统日期处理的转换
To遗留类From遗留类
java.time.Instant与java.util.DateDate.from(instant)date.tolnstant()
java.time.Instant与Java.sql.TimestampTimestamp.from(instant)timestamp.toInstant()
java.time.ZonedDateTime与java.util.GregorianCalendarGregorianCalendar.from(zonedDateTime)cal.toZonedDateTime()
java.time.LocalDate与java.sql.DateDate.valueOf(localDate)date.toLocalDate()
java.time.LocalTime与java.sql.TimeDate.valueOf(localTime)date.toLocalTime()
java.time.LocalDateTime与java.sql.TimestampTimestamp.valueOf(localDateTime)timestamp.toLocalDateTime()
java.time.Zoneld与java.util.TimeZoneTimezone.getTimeZone(id)timeZone.toZoneld()
java.time.format.DateTimeFormatter与java.text.DateFormatformatter.toFormat()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值