Java日期时间API

一、第一代

        

1、java.util.Date类,它里面很多方法都是已过时的。

* Date():获取系统时间
* long getTime():获取某个日期时间距离1970-1-1 0:0:0 的毫秒值

2、java.text.SimpleDateFormat:对日期进行格式化,或者把字符串按照某个模板转为日期时间值

 

package com.atguigu.dataapi;

import org.junit.Test;

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

public class TestDateApi {
    @Test
    public void test(){
        Date d1 = new Date();
        System.out.println(d1);//获取系统时间
    }

    @Test
    public void test1(){
        Date d2 = new Date();
        long l1 = d2.getTime();//距离1970 1-1 0:0:0的毫秒值
        System.out.println(l1);
    }

    @Test
    public void test3(){
        Date d3 = new Date(2024-1900,10-1,16);
        System.out.println(d3);
        long time = d3.getTime();
        System.out.println(time);

    }

    @Test
    public void test4(){
       // Date d4 = new Date();
        //System.out.println(d4);
        //Wed Oct 16 09:57:09 CST 2024

        String str = "Wed Oct 16 09:57:09 CST 2024";
        //使用simpleDateFormat()方法将字符串格式化为Date对象.
        // 定义输入日期的格式
        SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");

        try {
            // 将字符串解析为Date对象
            Date date = inputFormat.parse(str);

            // 定义输出日期的格式
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");

            // 将Date对象格式化为字符串
            String formattedDate = outputFormat.format(date);


            SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");//定义日期格式
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void test5() throws ParseException {
        //将str转换日期对象 利用simpleDateFormat()
        String str = "2024年10月15日 16时38分46秒";

        SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");//方法内为输出格式
        Date date = sf.parse(str);
        System.out.println(date);

    }

    @Test
    public void test6(){
        Date d = new Date();//无参构造
        System.out.println(d);//获取系统时间
        //Wed Oct 16 09:57:09 CST 2024

        SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒 E,这一天是这一年的第D天");//格式化样式
        String str = sf.format(d);
        System.out.println(str);
    }
}

二、第二代

        

1、java.util.TimeZone:时区

2、java.util.Locale:地区

3、java.util.Calendar:日历类型

package com.atguigu.dataapi;

import org.junit.Test;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class TestDateApi2<Timezone> {
    @Test
    public void test(){
        Calendar c = new GregorianCalendar();
        System.out.println(c);
        /*time=1729046106262,areFieldsSet=true,areAllFieldsSet=true,lenient=true,
        zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,
        lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2024,MONTH=9,WEEK_OF_YEAR=42
        ,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=290,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=10,HOUR_OF_DAY=10,MINUTE=35
        ,SECOND=6,MILLISECOND=262,ZONE_OFFSET=28800000,DST_OFFSET=0]*/

        /*基本信息
time=1729046106262:表示从1970年1月1日00:00:00 UTC到当前时间的毫秒数。
areFieldsSet=true:表示所有字段已经设置。
areAllFieldsSet=true:表示所有字段都已明确设置。
lenient=true:表示 Calendar 处于宽松模式,允许不严格的日期计算(例如,2024年2月30日会被自动调整为2024年3月2日)。
时区信息
zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null]:
id="Asia/Shanghai":表示时区为亚洲/上海。
offset=28800000:表示相对于UTC的时间偏移量,单位为毫秒(+8小时,即28800000毫秒)。
dstSavings=0:表示夏令时节省的时间,单位为毫秒(上海没有夏令时)。
useDaylight=false:表示该时区是否使用夏令时(上海不使用)。
transitions=31:表示该时区的历史变更次数。
lastRule=null:表示最后一个夏令时规则(上海没有夏令时,所以为null)。
周期和日期信息
firstDayOfWeek=1:表示一周的第一天是星期日(1表示星期日,2表示星期一)。
minimalDaysInFirstWeek=1:表示一周中至少需要多少天才能算作这一周的第一天(1表示只要有一天就算作一周的开始)。
日期字段
ERA=1:表示纪元(1表示公元)。
YEAR=2024:表示年份。
MONTH=9:表示月份(0表示1月,9表示10月)。
WEEK_OF_YEAR=42:表示一年中的第42周。
WEEK_OF_MONTH=3:表示一个月中的第3周。
DAY_OF_MONTH=16:表示一个月中的第16天。
DAY_OF_YEAR=290:表示一年中的第290天。
DAY_OF_WEEK=4:表示一周中的第4天(1表示星期日,4表示星期三)。
DAY_OF_WEEK_IN_MONTH=3:表示一个月中的第3个星期三。
时间字段
AM_PM=0:表示上午(0表示上午,1表示下午)。
HOUR=10:表示12小时制的小时数(10表示上午10点)。
HOUR_OF_DAY=10:表示24小时制的小时数(10表示10点)。
MINUTE=35:表示分钟数。
SECOND=6:表示秒数。
MILLISECOND=262:表示毫秒数。
时区偏移
ZONE_OFFSET=28800000:表示相对于UTC的时间偏移量,单位为毫秒(+8小时,即28800000毫秒)。
DST_OFFSET=0:表示夏令时偏移量,单位为毫秒(上海没有夏令时,所以为0)。*/

      int year = c.get(Calendar.YEAR);
      int month = c.get(Calendar.MONTH);
      int day = c.get(Calendar.DATE);
      int hours = c.get(Calendar.HOUR_OF_DAY);
      int minutes =  c.get(Calendar.MINUTE);

        System.out.println(year+"年" + month +"月"+day +"日" + hours +"时" + minutes +"分");
    }

    @Test
    public void test2(){
        Timezone zone = (Timezone) TimeZone.getTimeZone("Asia/Shanghai");//获取时区信息
        System.out.println(zone);
        //[id="Asia/Shanghai",offset=28800000,dstSavings=0,
        // useDaylight=false,transitions=31,lastRule=null]
        Calendar c = new GregorianCalendar((TimeZone) zone);
        System.out.println(c);
        /*time=1729046780438,areFieldsSet=true,areAllFieldsSet=true
        ,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,
        dstSavings=0,useDaylight=false,transitions=31,lastRule=null],
        firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,
        YEAR=2024,MONTH=9,WEEK_OF_YEAR=42,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,
        DAY_OF_YEAR=290,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=10,HOUR_OF_DAY=10
        ,MINUTE=46,SECOND=20,MILLISECOND=438,ZONE_OFFSET=28800000,DST_OFFSET=0]*/
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH)+1;
        int day = c.get(Calendar.DATE);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        System.out.println(year+"年" + month +"月"+day +"日" + hour +"时" + minute +"分");
    }
}

  三、第三代

第1代的问题:

* 无法表示不同时区的日期时间
* Date类很多API方法设计不够人性化,很麻烦
* 日期时间对象是可变的
* 线程不安全

第2代的问题:

* 日期时间对象是可变的
* 很难用,得到年、月、日等具体日期时间值时,需要调用get方法
* 线程不安全

第3代:从Java8引入,而且是参考了很多第三方的库设计的第3代。

3.1 本地日期类

* java.time.LocalDate
* java.time.LocalTime
* java.time.LocalDateTime

package com.atguigu.dataapi;

import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class TestDateApi3 {
    @Test
    public void test(){
        LocalDate today = LocalDate.now();
        //获取当前日期
        System.out.println(today);
    }

    @Test
    public void test2(){
        LocalTime now = LocalTime.now();
        System.out.println(now);
        //获取当前时间 时分秒
    }

    @Test
    public void test3(){
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);
        //年月日时分秒
    }

    @Test
    public void test4(){
        //用于创建一个 LocalDate 对象,表示一个特定的日期(年、月、日)。
        LocalDate birthday = LocalDate.of(2001,07,16);
        System.out.println(birthday);//2001-07-16
    }

    @Test
    public void test5(){
        LocalDate today = LocalDate.now();
        System.out.println(today);//2024-10-16
        LocalDate before = LocalDate.now().minusDays(100);//现在时间减去100天;
        System.out.println(before);//2024-07-08


    }
    @Test
    public void test6(){
        LocalDate l1 = LocalDate.of(2024,10,16);
        System.out.println(l1);//2024-10-16
        LocalDate l2 = l1.plusDays(200);
        System.out.println(l2);//2025-05-04
        //指定一个时间,创建一个LocalDate对象,使用plusDays方法,获取200天之后的日期
    }

    @Test
    public void test7(){
        LocalDate now = LocalDate.now();
        //获取当前日期
        boolean leapyear = now.isLeapYear();
        System.out.println(leapyear);
        //true,2024年是闰年
    }

    @Test
    public void test8(){
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        System.out.println("year = " + year);

        Month month = today.getMonth();
        System.out.println(month);//OCTOBER

        int monthValue = today.getMonthValue();
        System.out.println(monthValue);//10

        DayOfWeek dayOfWeek = today.getDayOfWeek();
        System.out.println(dayOfWeek);

        /*
        *getYear()//获取当前年份
        * getMonth()获取当前月份
        * getMonthValue()获取当前月份值
        * getDayOfWeek()获取当前星期值*/
    }

3.2 日期时间间隔

java.time.Period:日期间隔,阶段

java.time.Duration:时间间隔,或持续时间

 @Test
    public void test9(){
        LocalDate one = LocalDate.of(2024,9,23);
        LocalDate two = LocalDate.of(2000,10,6);

        Period p = Period.between(one,two);
        System.out.println(p);
        //P-23Y-11M-17D
        //获得一个Period ,包括两个日期之间的年数,月份和日期。
    }

    @Test
    public void test10(){
        LocalTime one = LocalTime.of(17,19);
        LocalTime two = LocalTime.of(21,45);
        Duration d = Duration.between(one,two);
        System.out.println(d);
        //PT4H26M
        //获取持续时间,如果对象的类型不同,则根据第一个对象的类型计算持续时间。
    }

    @Test
    public void test11(){
       /*
       ** java.time.ZoneId:时区id,例如:本地:Asia/Shanghai
        * java.time.ZoneOffset:时区偏移,例如:本地:+8:00
        * java.time.ZonedDateTime:某个时区的日期时间
        * java.time.Instant:本初子午线的瞬时 */
    }

3.3 不同时区的日期时间类

* java.time.ZoneId:时区id,例如:本地:Asia/Shanghai
* java.time.ZoneOffset:时区偏移,例如:本地:+8:00
* java.time.ZonedDateTime:某个时区的日期时间
* java.time.Instant:本初子午线的瞬时

package com.atguigu.api.date;

import org.junit.Test;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class TestDateTimeZone {
    @Test
    public void test1(){
        ZoneId id = ZoneId.of("America/Los_Angeles");
        ZonedDateTime z = ZonedDateTime.now(id);
        System.out.println(z);
        //2024-10-15T02:24:05.168998400-07:00[America/Los_Angeles]
    }

    @Test
    public void test2(){
        Instant instant = Instant.now();//本初子午线的瞬时
        System.out.println(instant);
        //2024-10-15T09:25:15.571756500Z
    }

    @Test
    public void test3(){
        ZoneId id = ZoneId.of("Asia/Shanghai");
        ZonedDateTime z = ZonedDateTime.now(id);
        System.out.println(z);
        //2024-10-15T17:26:00.193161900+08:00[Asia/Shanghai]
    }
}

3.4 日期时间格式化

java.time.format.DateTimeFormatter

  @Test
    public void test12(){
        //java.time.format.DateTimeFormatter
        LocalDateTime dateTime = LocalDateTime.now();
        //当前时间的年月日时分秒
        LocalDateTime datetime = LocalDateTime.now();
        //yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒 E,这一天是这一年的第D天
        DateTimeFormatter dt = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒 E,这一天是这一年的第D天");
        String str = dt.format(datetime);
        System.out.println(str);
        //2024年10月16日 11时41分13秒 101毫秒 周三,这一天是这一年的第290天
        //使用指定的模式创建格式化程序。格式2011-12-03,为“2011年12月3日
    }

    @Test
    public void test13(){
        //使用特定的格式化LocalDateTime从文本字符串获取LocalDateTime的实例
        String str = "2024年10月15日 16时38分46秒";
        DateTimeFormatter dt = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
        LocalDateTime dateTime = LocalDateTime.parse(str, dt);
        System.out.println(dateTime);
    }

    @Test
    public void test14(){
        //DateTimeFormatter.ofLocalizedDateTime 方法是 Java 8 引入的 java.time 包中的一个方法,用于根据本地化格式风格创建一个 DateTimeFormatter 对象。
        // 这个方法可以根据不同的 FormatStyle 生成不同格式的日期时间字符串。
        /*
        * FULL:完全格式,包含详细的日期和时间信息。
LONG:长格式,包含较多的日期和时间信息。
MEDIUM:中等格式,包含适中的日期和时间信息。
SHORT:短格式,包含最少的日期和时间信息。*/

        LocalDateTime datetime = LocalDateTime.now();
        DateTimeFormatter dt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.systemDefault());//全
        String str = dt.format(datetime);
        System.out.println(str);
        //withZone();添加时区方法,system default,系统默认时区
//        2024年10月16日星期三 中国标准时间 上午11:53:11
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值