[Java笔记13] 日期与时间

[Java笔记13] 日期与时间,第1张

[Java笔记13] 日期时间

目录

Date

Date的构造器

Date的常用方法

SimpleDateFormat

SimpleDateFormat的构造器

SimpleDateFormat的格式化方法

Calendar

Calendar日历类创建日历对象的方法

Calendar常用方法

JDK8新增日期类

LocalDate、LocalTime、LocalDateTime

Instant时间戳

DateTimeFormatter

Period

Duration

ChronoUnit


视频教程传送门 -> https://www.bilibili.com/video/BV1Cv411372m?p=118

Date

Date类代表当前所在系统的日期时间信息

Date的构造器

public Date() -> 创建一个Date对象,代表的是系统当前此刻日期时间

public Date(long time) -> 把时间毫秒值转换成Date日期对象

Date的常用方法

public long getTime()  -> 返回从1970年1月1日    00:00:00走到此刻的总的毫秒数

public void setTime(long time)  -> 设置日期对象的时间为当前时间毫秒值对应的时间

 => 时间毫秒值恢复成日期对象的两种方式,以上紫色
 

SimpleDateFormat

完成日期时间的格式化 *** 作

SimpleDateFormat的构造器

public SimpleDateFormat​(String pattern) -> 构造一个SimpleDateFormat,使用指定的格式

SimpleDateFormat的格式化方法

public final String format(Date date) -> 将日期格式化成日期/时间字符串

public final String format(Object time) -> 将时间毫秒值式化成日期/时间字符串

public Date parse​(String source) -> 从给定字符串的开始解析文本以生成日期

【例1】(1)格式化输出时间 -> 按照格式"yyyy年MM月dd日 HH:mm:ss EEE a" 输出当前时间,EEE代表星期几,a代表上午或下午  (2)解析字符串代表的时间并格式化输出

package com.test.d2_simpledateformat;

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


public class SimpleDateFormatDemo01 {
    public static void main(String[] args) {
        // 1、日期对象
        Date d = new Date();
        System.out.println(d);

        // 2、格式化这个日期对象 (指定最终格式化的形式)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
        // 3、开始格式化日期对象成为喜欢的字符串形式
        String rs = sdf.format(d);
        System.out.println(rs);

        System.out.println("----------------------------");

        // 4、格式化时间毫秒值
        // 需求:请问121秒后的时间是多少
        long time1 = System.currentTimeMillis() + 121 * 1000;
        String rs2 = sdf.format(time1);
        System.out.println(rs2);

    }
}

输出为:

【例2】计算出 2021年08月06日11点11分11秒,往后走2天14小时49分06秒后的时间是多少

package com.test.d2_simpledateformat;

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

public class SimpleDateFormatDemo2 {
    public static void main(String[] args) throws ParseException {
        // 目标: 学会使用SimpleDateFormat解析字符串时间成为日期对象。
        // 有一个时间 2021年08月06日 11:11:11 往后 2天 14小时 49分 06秒后的时间是多少。
        // 1、把字符串时间拿到程序中来
        String dateStr = "2021年08月06日 11:11:11";

        // 2、把字符串时间解析成日期对象(本节的重点):形式必须与被解析时间的形式完全一样,否则运行时解析报错!
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date d = sdf.parse(dateStr);

        // 3、往后走2天 14小时 49分 06秒
        long time = d.getTime() + (2L*24*60*60 + 14*60*60 + 49*60 + 6) * 1000;

        // 4、格式化这个时间毫秒值就是结果
        System.out.println(sdf.format(time));
    }
}

输出结果为:

2021年08月09日 02:00:17

需要注意的两个地方

=> 写到 Line16有个感叹号提示,是因为parse()中的内容需要严格匹配格式,注意仔细检查

确认无误,加上抛出异常即可

 => Line19中的计算部分加上了个"L",防止计算值超出int范围

【例3】判断顾客的付款时间是否在秒杀时间之内,会用到Date的before和after方法比较时间

package com.test.d2_simpledateformat;

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

public class SimpleDateFormatTest3 {
    public static void main(String[] args) throws ParseException {
        // 1、秒杀开始 和 结束时间
        String startTime = "2021-11-11 00:00:00";
        String endTime = "2021-11-11 00:10:00";

        // 2、小A 小B
        String xiaoA =  "2021-11-11 00:03:47";
        String xiaoB =  "2021-11-11 00:10:11";

        // 3、解析他们的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = sdf.parse(startTime);
        Date d2 = sdf.parse(endTime);
        Date d3 = sdf.parse(xiaoA);
        Date d4 = sdf.parse(xiaoB);

        if(d3.after(d1) && d3.before(d2)){
            System.out.println("小A秒杀成功,可以发货了!");
        }else {
            System.out.println("小B秒杀失败!");
        }

        if(d4.after(d1) && d4.before(d2)){
            System.out.println("小皮秒杀成功,可以发货了!");
        }else {
            System.out.println("小皮秒杀失败!");
        }
    }
}

 输出为:

小A秒杀成功,可以发货了!
小皮秒杀失败!

Calendar

Calendar代表了系统此刻日期对应的日历对象,Calendar是一个抽象类,不能直接创建对象。

Calendar日历类创建日历对象的方法

根据API文档,可以使用方法得到对象
        Calendar cal = Calendar.getInstance();
        System.out.println(cal);

输出如下,可以看到各个field的值        java.util.GregorianCalendar[time=1637679705878,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=2021,MonTH=10,WEEK_OF_YEAR=48,WEEK_OF_MonTH=4,DAY_OF_MonTH=23,DAY_OF_YEAR=327,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MonTH=4,AM_PM=1,HOUR=11,HOUR_OF_DAY=23,MINUTE=1,SECOND=45,MILLISECOND=878,ZONE_OFFSET=28800000,DST_OFFSET=0]

Calendar常用方法

public int get(int field) -> 取日期中的某个字段信息
public void set(int field,int value) -> 修改日历的某个字段信息
public void add(int field,int amount) -> 为某个字段增加/减少指定的值
public final Date getTime() -> 拿到此刻日期对象
public long getTimeInMillis() -> 拿到此刻时间毫秒值
 

JDK8新增日期类

LocalDate:不包含具体时间的日期。
LocalTime:不含日期的时间。
LocalDateTime:包含了日期及时间。
Instant:代表的是时间戳。
DateTimeFormatter 用于做时间的格式化和解析的
Duration:用于计算两个“时间”间隔 
Period:用于计算两个“日期”间隔
说明:新API的类型几乎全部是不变类型(和String的使用类似),可以放心使用不必担心被修改

LocalDate、LocalTime、LocalDateTime

类的实例是不可变的对象
构建对象和API都是通用的

构建对象方式
public static Xxxx now();   => 静态方法,根据当前时间创建对象
public static Xxxx of(…);   => 静态方法,指定日期/时间创建对象

获取信息的API
public int getYear()  -> 获取年
public int getMonthValue()  -> 获取月份(1-12)
public int getDayOfMonth()  -> 获取月中第几天
public int getDayOfMonth()  -> 获取年中第几天
public DayOfWeek getDayOfWeek()  -> 获取星期

修改相关的API
这些方法返回的是一个新的实例引用
plusDays, plusWeeks, plusMonths, plusYears
minusDays, minusWeeks, minusMonths, minusYears 
withDayOfMonth, withDayOfYear, withMonth, withYear -> 将月份天数、年份天数、月份、年 份 修 改 为 指 定 的 值 并 返 回 新 的 LocalDate 对象 
isBefore, isAfter 

【例】

package com.test.d4_jdk8_time;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.MonthDay;

public class Demo04UpdateTime {
    public static void main(String[] args) {
        LocalTime nowTime = LocalTime.now();
        System.out.println(nowTime);//当前时间
        System.out.println(nowTime.minusHours(1));//一小时前
        System.out.println("-----------------------------------");

        System.out.println(nowTime.plusMinutes(1));//一分钟后
        System.out.println("-----------------------------------");
        // 不可变对象,每次修改产生新对象!
        System.out.println(nowTime);
        System.out.println("-----------------------------------");

        LocalDate myDate = LocalDate.of(2016, 9, 5);
        LocalDate nowDate = LocalDate.now();

        System.out.println("今天是2016-09-06吗? " + nowDate.equals(myDate));//今天是2018-09-06吗? false
        System.out.println(myDate + "是否在" + nowDate + "之前? " + myDate.isBefore(nowDate));//2018-09-05是否在2018-09-06之前? true
        System.out.println(myDate + "是否在" + nowDate + "之后? " + myDate.isAfter(nowDate));//2018-09-05是否在2018-09-06之后? false
        System.out.println("-----------------------------------");

        // 判断今天是否是你的生日
        LocalDate birDate = LocalDate.of(1996, 8, 5);
        LocalDate nowDate1 = LocalDate.now();

        MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());
        MonthDay nowMd = MonthDay.from(nowDate1);

        System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));//今天是你的生日吗? false
    }
}

输出:

Instant时间戳

Instant类似JDK8以前的Date
Instant和Date这两个类可以进行转换
Instant instant = Instant.now();
Date date = Date.from(instant);
Instant instant2 = date.toInstant();

【例】

package com.test.d4_jdk8_time;

import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;

public class Demo05Instant {
    public static void main(String[] args) {
        // 1、得到一个Instant时间戳对象
        Instant instant = Instant.now();
        System.out.println(instant);

        // 2、得到系统本时区的时间戳
        Instant instant1 = Instant.now();
        System.out.println(instant1.atZone(ZoneId.systemDefault()));

        // 3、Instant对象返回Date对象
        Date date = Date.from(instant);
        System.out.println(date);

        // 4、Date对象返回Instant对象 
        Instant i2 = date.toInstant();
        System.out.println(i2);
    }
}

输出:

DateTimeFormatter

JDK8引入,正反都能调用format方法

【例】

package com.test.d4_jdk8_time;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Demo06DateTimeFormat {
    public static void main(String[] args) {
        // 本地此刻  日期时间 对象
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);

        // 解析/格式化器
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEE a");
        // 正向格式化
        System.out.println(dtf.format(ldt));
        // 逆向格式化
        System.out.println(ldt.format(dtf));

        // 解析字符串时间
        DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析当前字符串时间成为本地日期时间对象
        LocalDateTime ldt1 = LocalDateTime.parse("2019-11-11 11:11:11" ,  dtf1);
        System.out.println(ldt1);
        System.out.println(ldt1.getDayOfYear());
    }
}

输出:

Period

使用java.time.Period计算日期间隔
主要是通过 Period 类方法 getYears(),getMonths() 和 getDays() 计算,只能精确到年月日,用于 LocalDate 之间的比较。

【例】

package com.test.d4_jdk8_time;

import java.time.LocalDate;
import java.time.Period;

public class Demo07Period {
    public static void main(String[] args) {
        // 当前本地 年月日
        LocalDate today = LocalDate.now();
        System.out.println(today);//

        // 生日的 年月日
        LocalDate birthDate = LocalDate.of(1998, 10, 13);
        System.out.println(birthDate);

        Period period = Period.between(birthDate, today);//第二个参数减第一个参数

        System.out.println("年差值:" + period.getYears());
        System.out.println("月差值:" +period.getMonths());
        System.out.println("日差值:" +period.getDays());
    }
}

输出:

2021-11-27
1998-10-13
年差值:23
月差值:1
日差值:14

Duration

使用java.time.Duration计算时间间隔
用于 LocalDateTime 或 Instant 之间的比较

【例】

package com.test.d4_jdk8_time;

import java.time.Duration;
import java.time.LocalDateTime;

public class Demo08Duration {
    public static void main(String[] args) {
        // 本地日期时间对象。
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);

        // 出生的日期时间对象
        LocalDateTime birthDate = LocalDateTime.of(1998,10
                ,13,14,00,00);

        System.out.println(birthDate);

        Duration duration = Duration.between(  today , birthDate);//第二个参数减第一个参数

        System.out.println(duration.toDays());//两个时间差的天数
        System.out.println(duration.toHours());//两个时间差的小时数
    }
}

输出:

2021-11-27T14:00:41.006728600
1998-10-13T14:00
-8446
-202704

ChronoUnit

java.time.temporal.ChronoUnit工具类可用于在单个时间单位内测量一段时间,可以用于比较所有的时间单位

【例】

package com.test.d4_jdk8_time;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Demo09ChronoUnit {
    public static void main(String[] args) {
        // 本地日期时间对象:此刻的
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);

        // 生日时间
        LocalDateTime birthDate = LocalDateTime.of(1998,10,1,
                10,50,59);
        System.out.println(birthDate);

        System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today));
        System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today));
        System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today));
        System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today));
        System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today));
        System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today));
        System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today));
    }
}

输出:

2021-11-27T14:04:27.018881300
1998-10-01T10:50:59
相差的年数:23
相差的月数:277
相差的周数:1208
相差的天数:8458
相差的时数:202995
相差的分数:12179713
相差的秒数:730782808

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5612172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存