JDK8之前的时间:
Data类:
Date
类是 Java 中用于表示日期和时间的类之一,它在 java.util
包中定义。
Date
类的基本知识点
-
创建日期对象:
Date
类的无参构造函数创建一个表示当前日期和时间的对象。Date currentDate = new Date(); System.out.println(currentDate);
Date
类的构造函数可以接收一个表示自1970年1月1日(称为"Epoch")以来的毫秒数的参数:long millis = System.currentTimeMillis(); // 获取当前时间的毫秒数 Date specificDate = new Date(millis); System.out.println(specificDate);
-
Date
类的常用方法:getTime()
:返回自1970年1月1日00:00:00 GMT以来的毫秒数。long millis = currentDate.getTime(); System.out.println(millis);
setTime(long time)
:用给定的毫秒数设置日期。currentDate.setTime(millis + 1000); // 设置为当前时间的1秒后
-
比较Data对象的时间大小:
// time1和time2都已经创建好 Randomr=new Random(); //创建两个时间对象 Date d1 =new Date(Math.abs(r.nextInt())); Date d2 =new Date(Math.abs(r.nextInt())); long time1 = d1.getTime(); long time2 = d2.getTime(); if (time1 < time2) { System.out.println("date1 is earlier than date2"); } else if (time1 == time2) { System.out.println("date1 is equal to date2"); } else { System.out.println("date1 is later than date2"); }
- 打印时间原点开始一年之后的时间:
//需求1:打印时间原点开始一年之后的时间 //1.创建一个对象,表示时间原点 Date d1=new Date(0L); //2.获取d1时间的毫秒值 long time = d1.getTime(); //3.在这个基础上我们要加一年的亳秒值即可 time=time+1000L*60*60*24*365; //4.把计算之后的时间毫秒值,再设置回d1当中 d1.setTime(time); System.out.println(d1);
总结:
SimpleDateFormat:
SimpleDateFormat
是 Java 中用于格式化和解析日期和时间的类,它位于 java.text
包中。SimpleDateFormat
提供了将 Date
对象转换为指定格式的字符串,或者将字符串解析为 Date
对象的功能。
基本使用
-
创建
SimpleDateFormat
对象- 通过指定日期和时间的格式字符串,创建
SimpleDateFormat
对象:SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- 通过指定日期和时间的格式字符串,创建
-
格式化日期 (
Date
转字符串)- 使用
format()
方法将Date
对象转换为指定格式的字符串:import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class TestOfSimpleDateFormat { public static void main(String[] args) { // 指定格式使用带参构造创建SimpleDateFormat 对象 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); Date now = new Date(); String formattedDate = sdf1.format(now); System.out.println(formattedDate); // 输出格式如:2024-08-20 } }
- 使用
-
解析字符串 (
字符串转 Date
)- 使用
parse()
方法将符合格式的字符串解析为Date
对象:import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class TestOfSimpleDateFormat { public static void main(String[] args) throws ParseException { // 创建SimpleDateFormat对象的格式要和字符串的格式完全一致 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); // 创建所对应格式的SimpleDateFormat对象 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日"); // 解析字符串 String dateStr = "2024-08-20"; Date date = sdf1.parse(dateStr); // 格式化 String result = sdf2.format(date); System.out.println(result);// 输出:2024年08月20日 } }
- 使用
日期和时间格式化符号
SimpleDateFormat
使用的格式化符号表示不同的日期和时间元素:
- 年 (
y
):yyyy
表示四位数的年,yy
表示两位数的年。 - 月 (
M
):MM
表示月份的两位数字,MMM
表示月份的简写名称,MMMM
表示月份的全称。 - 日 (
d
):dd
表示月份中的天数。 - 小时 (
H
或h
):HH
表示24小时制,hh
表示12小时制。 - 分钟 (
m
):mm
表示分钟。 - 秒 (
s
):ss
表示秒。 - 毫秒 (
S
):SSS
表示毫秒。 - AM/PM (
a
): 标识上午或下午。 - 时区 (
z
或Z
):z
表示时区的缩写(如 PST),Z
表示时区的偏移量(如 -0800)。
示例
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestOfSimpleDateFormat {
public static void main(String[] args) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
SimpleDateFormat sdf3 = new SimpleDateFormat("hh:mm:ss a z");
SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
Date now = new Date();
System.out.println(sdf1.format(now));
// 输出: 2024-08-20
System.out.println(sdf2.format(now)); // 输出: Tuesday, August 20, 2024
System.out.println(sdf3.format(now)); // 输出: 03:45:30 PM PST
System.out.println(sdf4.format(now));// 输出:2024年08月20日 02:40:17
}
}
总结 :
Calendar:
Calendar概述:
Calendar代表了系统当前时间的日历对象,可以单独修改时间中的年,月,日.
细节:Calendar是一个抽象类,不能直接创建对象。
基本知识点
-
Calendar
的创建Calendar
是一个抽象类,不能直接实例化。可以使用其子类GregorianCalendar
或通过静态方法getInstance()
创建:Calendar calendar = Calendar.getInstance();
-
获取当前日期和时间
- 创建
Calendar
实例时,默认情况下会初始化为当前日期和时间。System.out.println(calendar.getTime()); // 输出当前日期和时间
- 创建
-
获取日期和时间的各个部分
- 可以使用
get(int field)
方法获取日期和时间的不同部分,如年、月、日、小时等。Calendar
类中定义了很多常量来表示这些部分,如Calendar.YEAR
、Calendar.MONTH
等:int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); // 注意:月从0开始,0表示1月 int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24小时制 System.out.println("Year: " + year + ", Month: " + (month + 1) + ", Day: " + day);
- 可以使用
-
设置日期和时间
-
使用
set(int field, int value)
方法可以设置日期和时间的某个部分:calendar.set(Calendar.YEAR, 2025); // 月份从0开始,12表示12月 calendar.set(Calendar.MONTH, 12); calendar.set(Calendar.DAY_OF_MONTH, 25); System.out.println(calendar.getTime()); // 输出:2025-12-25
-
还可以一次性设置年、月、日、时、分、秒:
calendar.set(2025, Calendar.DECEMBER, 25, 15, 30, 45); System.out.println(calendar.getTime()); // 输出:2025-12-25 15:30:45
-
-
日期加减操作
- 使用
add(int field, int amount)
方法可以对日期和时间进行加减操作。例如,加减天数、月份或年份:calendar.add(Calendar.DAY_OF_MONTH, 10); // 日期加10天 System.out.println(calendar.getTime()); calendar.add(Calendar.MONTH, -2); // 月份减2个月 System.out.println(calendar.getTime());
- 使用
总结:
JDK8之后:
细节:
IDK8新增的时间对象都是不可变的如果我们修改了,减少了,增加了时间那么调用者是不会发生改变的,产生一个新的时间。
Zoneld时区:
import java.time.ZoneId;
import java.util.Set;
public class JDK8Data {
public static void main(String[] args) {
/* static Set<String> getAvailableZoneIds();获取Java中支持的所有时区
static ZoneId systemDefault() 获取系统默认时区
static zoneId of(string zoneId) 获取一个指定时区
*/
//1.获取所有的时区名称
Set<String>zoneIds =ZoneId.getAvailableZoneIds();
System.out.println(zoneIds.size());//603
System.out.println(zoneIds);//所有的时区名称
//2.获取当前系统的默认时区
ZoneId zoneId =ZoneId.systemDefault();
System.out.println(zoneId);//Asia/shanghai
//3.获取指定的时区
ZoneId z = ZoneId.of("Asia/Aden");
System.out.println(z);
}
}
Instant时间戳:
主要知识点
-
Instant
的创建-
Instant
可以表示从标准时间(UTC 1970-01-01T00:00:00Z)开始的时间点。 -
主要方法:
now()
:获取当前的时间戳。ofEpochSecond(long epochSecond)
:通过秒数创建Instant
对象。ofEpochMilli(long epochMilli)
:通过毫秒数创建Instant
对象。parse(CharSequence text)
:通过字符串解析Instant
对象。
// 当前时间戳 Instant instantNow = Instant.now(); // 秒级时间戳 Instant instantFromEpochSecond = Instant.ofEpochSecond(1623844800); // 毫秒级时间戳 Instant instantFromEpochMilli = Instant.ofEpochMilli(1623844800000L); // 解析字符串 Instant instantFromString = Instant.parse("2024-08-20T10:45:30.00Z");
-
-
时间戳的加减操作
-
Instant
提供了一些方法用于加减时间:plusSeconds(long seconds)
:增加指定的秒数。minusMillis(long millis)
:减少指定的毫秒数。plus(Duration duration)
:增加指定的持续时间。minus(Duration duration)
:减少指定的持续时间。
// 加60秒 Instant instantPlus = instantNow.plusSeconds(60); // 减1000毫秒 Instant instantMinus = instantNow.minusMillis(1000);
-
时间戳的比较
-
Instant
可以通过isBefore(Instant otherInstant)
、isAfter(Instant otherInstant)
和equals(Object other)
方法进行比较。Instant instant1 = Instant.now(); Instant instant2 = Instant.now().plusSeconds(10); boolean isBefore = instant1.isBefore(instant2); // true boolean isAfter = instant1.isAfter(instant2); // false boolean isEqual = instant1.equals(instant2); // false
ZoneDateTime:带时区的时间:
1. 获取当前时间的 ZonedDateTime
对象
-
static ZonedDateTime now()
- 获取当前系统默认时区的日期时间。
ZonedDateTime now = ZonedDateTime.now(); // 当前系统默认时区的时间
-
static ZonedDateTime now(ZoneId zone)
- 获取指定时区的当前日期时间。
ZonedDateTime nowInParis = ZonedDateTime.now(ZoneId.of("Europe/Paris")); // 巴黎时区的当前时间
2. 创建指定时间的 ZonedDateTime
对象
-
static ZonedDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone)
-
使用指定的日期和时间以及时区创建
ZonedDateTime
对象。ZonedDateTime specificDateTime = ZonedDateTime.of(2024, 8, 20, 10, 30, 0, 0, ZoneId.of("America/New_York"));
3. 修改时间系列的方法
-
ZonedDateTime with(TemporalField field, long newValue)
- 修改特定字段的值,并返回新的
ZonedDateTime
对象。例如,修改年、月、日等。
ZonedDateTime updatedDateTime = now.with(ChronoField.YEAR, 2025); // 将年份设置为2025
- 修改特定字段的值,并返回新的
-
ZonedDateTime withYear(int year)
- 修改年份,并返回新的
ZonedDateTime
对象。
ZonedDateTime updatedYear = now.withYear(2025); // 设置年份为2025
- 修改年份,并返回新的
-
ZonedDateTime withMonth(int month)
- 修改月份,并返回新的
ZonedDateTime
对象。
ZonedDateTime updatedMonth = now.withMonth(12); // 设置月份为12月
- 修改月份,并返回新的
-
ZonedDateTime withDayOfMonth(int dayOfMonth)
- 修改日期,并返回新的
ZonedDateTime
对象。
ZonedDateTime updatedDay = now.withDayOfMonth(15); // 设置日期为15
- 修改日期,并返回新的
-
ZonedDateTime withHour(int hour)
- 修改小时,并返回新的
ZonedDateTime
对象。
ZonedDateTime updatedHour = now.withHour(14); // 设置小时为14
- 修改小时,并返回新的
-
ZonedDateTime withMinute(int minute)
- 修改分钟,并返回新的
ZonedDateTime
对象。
ZonedDateTime updatedMinute = now.withMinute(45); // 设置分钟为45
- 修改分钟,并返回新的
-
ZonedDateTime withSecond(int second)
- 修改秒,并返回新的
ZonedDateTime
对象。
ZonedDateTime updatedSecond = now.withSecond(30); // 设置秒为30
- 修改秒,并返回新的
-
ZonedDateTime withNano(int nanoOfSecond)
- 修改纳秒,并返回新的
ZonedDateTime
对象。
ZonedDateTime updatedNano = now.withNano(500000000); // 设置纳秒为500百万
- 修改纳秒,并返回新的
4. 增加时间系列的方法
-
ZonedDateTime plus(TemporalAmount amountToAdd)
- 增加指定的时间量,返回新的
ZonedDateTime
对象。
ZonedDateTime later = now.plus(Duration.ofHours(3)); // 增加3小时
- 增加指定的时间量,返回新的
-
ZonedDateTime plusYears(long years)
- 增加指定的年份,返回新的
ZonedDateTime
对象。
ZonedDateTime laterYear = now.plusYears(2); // 增加2年
- 增加指定的年份,返回新的
-
ZonedDateTime plusMonths(long months)
- 增加指定的月份,返回新的
ZonedDateTime
对象.
ZonedDateTime laterMonth = now.plusMonths(6); // 增加6个月
- 增加指定的月份,返回新的
-
ZonedDateTime plusDays(long days)
- 增加指定的天数,返回新的
ZonedDateTime
对象.
ZonedDateTime laterDay = now.plusDays(15); // 增加15天
- 增加指定的天数,返回新的
-
ZonedDateTime plusHours(long hours)
- 增加指定的小时数,返回新的
ZonedDateTime
对象.
ZonedDateTime laterHour = now.plusHours(4); // 增加4小时
- 增加指定的小时数,返回新的
-
ZonedDateTime plusMinutes(long minutes)
- 增加指定的分钟数,返回新的
ZonedDateTime
对象.
ZonedDateTime laterMinute = now.plusMinutes(45); // 增加45分钟
- 增加指定的分钟数,返回新的
-
ZonedDateTime plusSeconds(long seconds)
- 增加指定的秒数,返回新的
ZonedDateTime
对象.
ZonedDateTime laterSecond = now.plusSeconds(90); // 增加90秒
- 增加指定的秒数,返回新的
DateTimeFormatter用于时间的格式化和解析:
DateTimeFormatter
类
DateTimeFormatter
用于格式化和解析日期时间对象,类似于旧的 SimpleDateFormat
,但它是线程安全的。
主要方法:
ofPattern(String pattern)
:根据给定的模式创建DateTimeFormatter
对象。format(TemporalAccessor temporal)
:将日期时间对象格式化为字符串。parse(CharSequence text, TemporalQuery query)
:将符合格式的字符串解析为日期时间对象。
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;
public class JDK8Data {
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));
}
}
日历类:
-
LocalDate
-
表示没有时间的日期,例如生日或假期。
-
只包含日期部分(年、月、日),不包含时间部分和时区信息。
-
主要方法:
now()
:获取当前日期。of(int year, int month, int dayOfMonth)
:创建特定日期。plusDays(long days)
、minusDays(long days)
:日期加减操作。getYear()
、getMonth()
、getDayOfMonth()
:获取年份、月份和日期。
LocalDate date = LocalDate.now(); LocalDate birthday = LocalDate.of(1990, Month.JANUARY, 1);
-
-
LocalTime
-
表示一天中的时间,不包含日期部分和时区信息。
-
包含时间部分(小时、分钟、秒、纳秒)。
-
主要方法:
now()
:获取当前时间。of(int hour, int minute, int second)
:创建特定时间。plusHours(long hours)
、minusMinutes(long minutes)
:时间加减操作。
LocalTime time = LocalTime.now(); LocalTime meeting = LocalTime.of(10, 30);
-
-
LocalDateTime
-
表示日期和时间,不包含时区信息。
-
包含日期和时间部分(年、月、日、时、分、秒、纳秒)。
-
主要方法:
now()
:获取当前日期和时间。of(int year, int month, int dayOfMonth, int hour, int minute)
:创建特定日期时间。plusDays(long days)
、minusHours(long hours)
:日期时间加减操作。
LocalDateTime now = LocalDateTime.now(); LocalDateTime specificDateTime = LocalDateTime.of(2024, Month.AUGUST, 20, 10, 45);
-
工具类:
计算时间间隔
Period:
//当前本地 年月日
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);//P22Y6M17D
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
// 获取相隔了多少月份
System.out.println(period.toTotalMonths());//270
Duration:
//本地日期时间对象。
LocalDateTime today=LocalDateTime.now();
System.out.println(today);
//出生的日期时间对象
LocalDateTime birthDate = LocalDateTime.of(2000,11,0,00,00);
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());//两个时间差的纳秒数
ChronoUnit:
// 当前时间
LocalDateTime today=LocalDateTime.now();
System.out.println(today);
// 生日时间
LocalDateTime birthDate = LocalDateTime.of( 2000, 1, 1,hour: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.printin("相差的周数:"+ 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));