java时间API

世界标准时间UTC : 原子钟

中国标准时间 : 世界标准+8小时

Date时间类

Date类是一个JDK写好的javabean类,用来描述时间,精确到毫秒

利用空参构造创建的对象,默认表示系统当前的时间

利用有参构造创建的对象,表示指定的时间

public class Date{
	private long time; //当前时间的毫秒值
	public Date(){ //空参构造方法
		this.time = System.currentTimeMillis();
	}
	public Date(long time){ //带参构造方法
		this.time = time;
	}
	public void setTime(){
		this.time = time;
	}
	public void getTime(){
		return time;
	}

方法

说明

public Date()

创建Date对象,表示当前时间

public Date(long date)

创建Date对象,表示指定时间

public void setTime(long time)

设置/修改毫秒值

public long getTime()

获取时间对象的毫秒值

### 练习

import java.util.Date;  
  
public class TimeTest1 {  
    public static void main(String[] args) {  
        /*  
        * 需求:打印时间原点开始一年后的时间  
        * */        //需求1:打印时间原点开始一年之后的时间  
        //1.创建一个对象,表示时间原点  
        Date date = new Date(0L);  
        //2.获取时间的毫秒值  
        long time = date.getTime();  
        //3.在这个基础上加上一年的毫秒值  
        time = time + 1000L*60*60*24*365;  
        //4.把计算之后的时间毫秒值,再设置  
        date.setTime(time);  
        System.out.println(date);  
    }  
}

SimpleDateFormat类作用

  • 格式化 : 把时间变成常用的格式(2023年1月1日;2023-1-1;2023/1/1)

  • 解析 : 把字符串表示的时间变成Date对象

构造方法

说明

public SimpleDateFormat()

构造一个SimpleDateFormat,使用默认格式

public SimpleDateFormat(String pattern)

构造一个SimpleDateFormat,使用指定的格式

常用方法

说明

public final String format(Date date)

格式化(日期对象 -> 字符串)

public Date parse(String source)

解析(字符串 -> 日期对象)

### 格式化的时间形式的常用的模式对应关系

y 年

M 月

d 日

H 时

m 分

s 秒

2023-1-1 00:00:00
yyyy-M-d HH:mm:ss

字母

日期或时间元素

表示

示例

G

Era 标志符

Text

AD

y

Year

1996; 96

M

年中的月份

Month

July; Jul; 07

w

年中的周数

Number

27

W

月份中的周数

Number

2

D

年中的天数

Number

189

d

月份中的天数

Number

10

F

月份中的星期

Number

2

E

星期中的天数

Text

Tuesday; Tue

a

Am/pm 标记

Text

PM

H

一天中的小时数(0-23)

Number

0

k

一天中的小时数(1-24)

Number

24

K

am/pm 中的小时数(0-11)

Number

0

h

am/pm 中的小时数(1-12)

Number

12

m

小时中的分钟数

Number

30

s

分钟中的秒数

Number

55

S

毫秒数

Number

978

z

时区

General time zone

Pacific Standard Time; PST; GMT-08:00

Z

时区

RFC 822 time zone

-800

import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
  
public class SimpleDateFormatDemo1 {  
    public static void main(String[] args) throws ParseException {  
        //1.利用空参构造创件SimpleDateFormat对象,默认格式  
        SimpleDateFormat simpleDateFormatDemo1 = new SimpleDateFormat();  
        Date date = new Date(0L);  
        //format格式化(日期对象 转为 字符串)  
        String st = simpleDateFormatDemo1.format(date);  
        System.out.println(st);  
  
        //2.利用带参构造创件SimpleDateFormat对象,指定格式  
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy年M月d日 HH:mm:ss EE");  
        String st1 = simpleDateFormat1.format(date);  
        System.out.println(st1);  
  
        //3.定义一个字符串表示时间  
        String stTime = "2023-01-01 11:11:11";  
        //利用有参构造创件SimpleDateFormat对象  
        //创建对象的格式要和字符串的格式完全一样  
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date date1 = simpleDateFormat2.parse(stTime);  
        System.out.println(date1);  
        System.out.println(date1.getTime());  
    }  
}

练习

import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
  
public class SimpleDateFormatTest1 {  
    public static void main(String[] args) throws ParseException {  
        /*将出生年月日:2000-11-11  
        * 用字符串表示这个数据,并将其转换为2000年11月11日*/  
        //1.通过对2000-11-11解析,解析成一个Date对象  
        String st = "2000-11-11";  
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");  
        Date date = simpleDateFormat.parse(st);  
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy年MM月dd日");  
        String s = simpleDateFormat1.format(date);  
        System.out.println(s);  
    }  
}

Calendar概述

  • Calendar代表了系统当前时间的日历对象,可以单独修改,获取时间中的年、月、日

  • Calendar是一个抽象类,不能直接创建对象

获取Calendar日历对象的方法

f方法名

说明

public static Calendar getInstance()

获取当前时间的日历对象

### 常用方法

方法名

说明

public final Date getTime()

获取日期对象

public final setTime(Date date)

给日历设置日期对象

public long getTimeInMillis()

拿到时间毫秒值

public void setTimeInMillis(long millis)

给日历设置时间毫秒值

public int get(int field)

取日历中的某个字段信息

public void set(int field,int value)

修改日历的某个字段信息

public void add(int field,int amount)

为某个字段增加/减少指定的值

Calendar是一个抽象类,不能直接new,而是通过一个静态方法获取到子类对象
底层原理
会根据系统的不同时区来获取不同的日历对象,默认表示当前时间
把时间中的纪元,年,月,日,时,分,秒,星期,等等都方法哦一个数组中
0索引表示纪元
1索引表示年
2索引表示月
3索引表示一年中的第几周
4索引表示一个月中的第几周
5索引表示一个月中的第几天(日期)
java在Calendar类中,把索引对应的数字都定义成常量
月份0-11,如果获取出来的是0,实际表示1月,星期日是一周中的第一天
import java.util.Calendar;  
import java.util.Date;  
  
public class CalendarDemo1 {  
    public static void main(String[] args) {  
        //1.获取日历对象  
        Calendar calendar = Calendar.getInstance();  
        System.out.println(calendar);  
        //2.修改一下日历代表的时间  
        Date date = new Date(0L);  
        calendar.setTime(date);  
        System.out.println(calendar);  
  
        //3.获取数组中具体信息  
        int year = calendar.get(Calendar.YEAR);  
        int month = calendar.get(Calendar.MONTH) +1;  
        int date1 = calendar.get(Calendar.DAY_OF_MONTH);  
        System.out.println(year+","+month+","+date1);  
  
        //4.修改时间  
        calendar.set(Calendar.YEAR,2023);  
        year = calendar.get(Calendar.YEAR);  
        System.out.println(year);  
  
        //5.增删  
        calendar.add(Calendar.YEAR,1);  
        year = calendar.get(Calendar.YEAR);  
        System.out.println(year);  
    }  
}

JDK8新增时间类

时间日期对象都是不可变的

ZoneId时区

洲名/城市名

国家名/城市名

方法名

说明

static Set<String> getAvailableZoneIds()

获取Java中支持的所有时区

static ZoneId systemDefault()

获取系统默认时区

static ZoneId of(String zoneId)

获取一个指定时区

import java.time.ZoneId;  
import java.util.Set;  
  
public class ZoneIdDemo1 {  
    public static void main(String[] args) {  
        //1.获取所有的时区名称  
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();  
        System.out.println(zoneIds);  
  
        //2.获取当前系统的默认时区  
        ZoneId zoneId = ZoneId.systemDefault();  
        System.out.println(zoneId);//Asia/Shanghai  
  
        //3.获取指定时区  
        ZoneId of = ZoneId.of("America/Marigot");  
        System.out.println(of);  
    }  
}

Instant时间戳

方法名

说明

static Instant now()

获取当前时间的Instant对象(标准时间)

static Instant ofXxx(long epochMilli)

根据(秒/毫秒纳秒/)获取Instant对象

ZonedDateTime atZone(ZoneId zone)

指定时区

boolean isXxx(Instant otherInstant)

判断系列的方法

Instant minusXxx(long MillisToSubtract)

减少时间序列的方法

Instant plusXxx(long MillisToSubtract)

增加时间序列的方法

isBefore: 判断调用者代表的时间是否在参数表示时间的前面
isAfter: 判断调用者代表的时间是否在参数表示时间的后面
import java.time.Instant;  
import java.time.ZoneId;  
import java.time.ZonedDateTime;  
  
public class InstantDemo {  
    public static void main(String[] args) {  
        //1.获取当前时间的Instant对象(标准时间)  
        Instant now = Instant.now();  
        System.out.println(now);  
  
        //2.根据(秒/毫秒纳秒/)获取Instant对象  
        Instant instant = Instant.ofEpochMilli(0L);//毫秒  
        System.out.println(instant);  
  
        Instant instant1 = Instant.ofEpochSecond(1L); //秒  
        System.out.println(instant1);  
  
        Instant instant2 = Instant.ofEpochSecond(1L, 1000000000L); //纳秒  
        System.out.println(instant2);  
  
        //3.指定时区  
        ZonedDateTime zonedDateTime = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));  
        System.out.println(zonedDateTime);  
  
        //4.判断  
        //isBefore: 判断调用者代表的时间是否在参数表示时间的前面  
        //isAfter: 判断调用者代表的时间是否在参数表示时间的后面  
        Instant instant3 = Instant.ofEpochMilli(0L);  
        Instant instant4 = Instant.ofEpochMilli(1000L);  
        boolean res = instant3.isBefore(instant4);  
        System.out.println(res);  
  
        boolean res2 = instant3.isAfter(instant4);  
        System.out.println(res2);  
  
        //5.增减时间序列  
        Instant instant5 = Instant.ofEpochMilli(3000L);  
        System.out.println(instant5);  
  
        Instant instant6 = instant5.minusMillis(1000L);//减1秒  
        System.out.println(instant6);  
  
        Instant instant7 = instant5.plusMillis(1000L);//加1秒  
        System.out.println(instant7);  
    }  
}

ZoneDateTime带时区的时间

方法名

说明

static ZoneDateTime now()

获取当前时间的ZoneDateTime对象

static ZoneDateTime ofXxx(...)

获取指定时间的ZoneDateTime对象

ZoneDateTime withXxx(时间)

修改时间序列的方法

ZoneDateTime minusXxx(时间)

减少时间序列的方法

ZoneDateTime plusXxx(时间)

增加时间序列的方法

import java.time.Instant;  
import java.time.ZoneId;  
import java.time.ZonedDateTime;  
  
public class ZoneDateTimeDemo {  
    public static void main(String[] args) {  
        /*  
            static ZonedDateTime now() 获取当前时间的ZonedDateTime对象  
            static ZonedDateTime ofXxxx(。。。) 获取指定时间的ZonedDateTime对象  
            ZonedDateTime withXxx(时间) 修改时间系列的方法  
            ZonedDateTime minusXxx(时间) 减少时间系列的方法  
            ZonedDateTime plusXxx(时间) 增加时间系列的方法  
         */        //1.获取当前时间对象(带时区)  
        ZonedDateTime now = ZonedDateTime.now();  
        System.out.println(now);  
  
        //2.获取指定的时间对象(带时区)1/年月日时分秒纳秒方式指定  
        ZonedDateTime time1 = ZonedDateTime.of(2023, 10, 1,  
                11, 12, 12, 0, ZoneId.of("Asia/Shanghai"));  
        System.out.println(time1);  
  
        //通过Instant + 时区的方式指定获取时间对象  
        Instant instant = Instant.ofEpochMilli(0L);  
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");  
        ZonedDateTime time2 = ZonedDateTime.ofInstant(instant, zoneId);  
        System.out.println(time2);  
  
  
        //3.withXxx 修改时间系列的方法  
        ZonedDateTime time3 = time2.withYear(2000);  
        System.out.println(time3);  
  
        //4. 减少时间  
        ZonedDateTime time4 = time3.minusYears(1);  
        System.out.println(time4);  
  
        //5.增加时间  
        ZonedDateTime time5 = time4.plusYears(1);  
        System.out.println(time5);  
  
  
    }  
}

DateTimeFormatter 用于时间的格式化和解析

方法名

说明

static DateTimeFormatter ofPattern(格式)

获取格式对象

String format(时间对象)

按照指定方式格式化

import java.time.Instant;  
import java.time.ZoneId;  
import java.time.ZonedDateTime;  
import java.time.format.DateTimeFormatter;  
  
public class DateTimeFormatterDemo {  
    public static void main(String[] args) {  
        /*  
            static DateTimeFormatter ofPattern(格式) 获取格式对象  
            String format(时间对象) 按照指定方式格式化  
        */        //获取时间对象  
        ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));  
  
        // 解析/格式化器  
        DateTimeFormatter dtf1=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm;ss EE a");  
        // 格式化  
        System.out.println(dtf1.format(time));  
    }  
}

Calendar日历类

  • LocalDate : 年月日

  • LocalTime : 时分秒

  • LocalDateTime : 年月日时分秒

方法名

说明

static XXX now()

获取当前时间的对象

static XXX of(...)

获取值指定时间的对象

get开头的方法

获取日历中的年、月、日、时、分、秒等信息

isBefore,isAfter

比较两个LocalDate

with开头的

修改时间序列的方法

minus开头的

减少时间序列的方法

plus开头的

增加时间序列的方法

LocalDateTime可以转成LocalDate对象和LocalTime对象,使用toLocalDate()和toLocalTime()方法

LocalDate
import java.time.DayOfWeek;  
import java.time.LocalDate;  
import java.time.Month;  
import java.time.MonthDay;  
  
public class LocalDateDemo {  
    public static void main(String[] args) {  
        //1.获取当前时间的日历对象(包含 年月日)  
        LocalDate nowDate = LocalDate.now();  
        System.out.println("今天的日期:" + nowDate);  
        //2.获取指定的时间的日历对象  
        LocalDate ldDate = LocalDate.of(2023, 1, 1);  
        System.out.println("指定日期:" + ldDate);  
  
        System.out.println("=============================");  
  
        //3.get系列方法获取日历中的每一个属性值//获取年  
        int year = ldDate.getYear();  
        System.out.println("year: " + year);  
        //获取月//方式一:  
        Month m = ldDate.getMonth();  
        System.out.println(m);  
        System.out.println(m.getValue());  
  
        //方式二:  
        int month = ldDate.getMonthValue();  
        System.out.println("month: " + month);  
  
  
        //获取日  
        int day = ldDate.getDayOfMonth();  
        System.out.println("day:" + day);  
  
        //获取一年的第几天  
        int dayofYear = ldDate.getDayOfYear();  
        System.out.println("dayOfYear:" + dayofYear);  
  
        //获取星期  
        DayOfWeek dayOfWeek = ldDate.getDayOfWeek();  
        System.out.println(dayOfWeek);  
        System.out.println(dayOfWeek.getValue());  
  
        //is开头的方法表示判断  
        System.out.println(ldDate.isBefore(ldDate));  
        System.out.println(ldDate.isAfter(ldDate));  
  
        //with开头的方法表示修改,只能修改年月日  
        LocalDate withLocalDate = ldDate.withYear(2000);  
        System.out.println(withLocalDate);  
  
        //minus开头的方法表示减少,只能减少年月日  
        LocalDate minusLocalDate = ldDate.minusYears(1);  
        System.out.println(minusLocalDate);  
  
  
        //plus开头的方法表示增加,只能增加年月日  
        LocalDate plusLocalDate = ldDate.plusDays(1);  
        System.out.println(plusLocalDate);  
  
        //-------------  
        // 判断今天是否是你的生日  
        LocalDate birDate = LocalDate.of(2000, 1, 1);  
        LocalDate nowDate1 = LocalDate.now();  
  
        MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());  
        MonthDay nowMd = MonthDay.from(nowDate1);  
  
        System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));//今天是你的生日吗?  
    }  
}
LocalTime
import java.time.LocalTime;  
  
public class LocalTimeDemo {  
    public static void main(String[] args) {  
        // 获取本地时间的日历对象。(包含 时分秒)  
        LocalTime nowTime = LocalTime.now();  
        System.out.println("今天的时间:" + nowTime);  
  
        int hour = nowTime.getHour();//时  
        System.out.println("hour: " + hour);  
  
        int minute = nowTime.getMinute();//分  
        System.out.println("minute: " + minute);  
  
        int second = nowTime.getSecond();//秒  
        System.out.println("second:" + second);  
  
        int nano = nowTime.getNano();//纳秒  
        System.out.println("nano:" + nano);  
        System.out.println("------------------------------------");  
        System.out.println(LocalTime.of(8, 20));//时分  
        System.out.println(LocalTime.of(8, 20, 30));//时分秒  
        System.out.println(LocalTime.of(8, 20, 30, 150));//时分秒纳秒  
        LocalTime mTime = LocalTime.of(8, 20, 30, 150);  
  
        //is系列的方法  
        System.out.println(nowTime.isBefore(mTime));  
        System.out.println(nowTime.isAfter(mTime));  
  
        //with系列的方法,只能修改时、分、秒  
        System.out.println(nowTime.withHour(10));  
  
        //plus系列的方法,只能修改时、分、秒  
        System.out.println(nowTime.plusHours(10));  
    }  
}
LocalDateTime
import java.time.LocalDate;  
import java.time.LocalDateTime;  
import java.time.LocalTime;  
  
public class LocalDateTimeDemo {  
    public static void main(String[] args) {  
        // 当前时间的的日历对象(包含年月日时分秒)  
        LocalDateTime nowDateTime = LocalDateTime.now();  
  
        System.out.println("今天是:" + nowDateTime);//今天是:  
        System.out.println(nowDateTime.getYear());//年  
        System.out.println(nowDateTime.getMonthValue());//月  
        System.out.println(nowDateTime.getDayOfMonth());//日  
        System.out.println(nowDateTime.getHour());//时  
        System.out.println(nowDateTime.getMinute());//分  
        System.out.println(nowDateTime.getSecond());//秒  
        System.out.println(nowDateTime.getNano());//纳秒  
        // 日:当年的第几天  
        System.out.println("dayofYear:" + nowDateTime.getDayOfYear());  
        //星期  
        System.out.println(nowDateTime.getDayOfWeek());  
        System.out.println(nowDateTime.getDayOfWeek().getValue());  
        //月份  
        System.out.println(nowDateTime.getMonth());  
        System.out.println(nowDateTime.getMonth().getValue());  
  
        LocalDate ld = nowDateTime.toLocalDate();  
        System.out.println(ld);  
  
        LocalTime lt = nowDateTime.toLocalTime();  
        System.out.println(lt.getHour());  
        System.out.println(lt.getMinute());  
        System.out.println(lt.getSecond());  
    }  
}

工具类

  • Duration 用于计算两个“时间”间隔(秒,纳秒)

  • Period 用于计算两个“日期”间隔(年月日)

  • ChronoUnit 用于计算两个“日期”间隔

Duration
import java.time.Duration;  
import java.time.LocalDateTime;  
  
public class DurationDemo {  
    public static void main(String[] args) {  
        // 本地日期时间对象。  
        LocalDateTime today = LocalDateTime.now();  
        System.out.println(today);  
  
        // 出生的日期时间对象  
        LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1, 0, 0, 0);  
        System.out.println(birthDate);  
  
        Duration duration = Duration.between(birthDate, today);//第二个参数减第一个参数  
        System.out.println("相差的时间间隔对象:" + duration);  
  
        System.out.println("============================================");  
        System.out.println(duration.toDays());//两个时间差的天数  
        System.out.println(duration.toHours());//两个时间差的小时数  
        System.out.println(duration.toMinutes());//两个时间差的分钟数  
        System.out.println(duration.toMillis());//两个时间差的毫秒数  
        System.out.println(duration.toNanos());//两个时间差的纳秒数  
    }  
}
Period
import java.time.LocalDate;  
import java.time.Period;  
  
public class PeriodDemo {  
    public static void main(String[] args) {  
        // 当前本地 年月日  
        LocalDate today = LocalDate.now();  
        System.out.println(today);  
  
        // 生日的 年月日  
        LocalDate birthDate = LocalDate.of(2000, 1, 1);  
        System.out.println(birthDate);  
  
        Period period = Period.between(birthDate, today);//第二个参数减第一个参数  
  
        System.out.println("相差的时间间隔对象:" + period);  
        System.out.println(period.getYears());  
        System.out.println(period.getMonths());  
        System.out.println(period.getDays());  
  
        System.out.println(period.toTotalMonths());  
    }  
}
ChronoUnit
import java.time.LocalDateTime;  
import java.time.temporal.ChronoUnit;  
  
public class ChronoUnitDemo {  
    public static void main(String[] args) {  
        // 当前时间  
        LocalDateTime today = LocalDateTime.now();  
        System.out.println(today);  
        // 生日时间  
        LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1,0, 0, 0);  
        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));  
        System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today));  
        System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today));  
        System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today));  
        System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today));  
        System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today));  
        System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today));  
        System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today));  
        System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));  
    }  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尘世烟雨客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值