一.新增时间日期API
1.概述
A:
Date
SimpleDateFormat
Calendar
线程不安全,jdk1.8新增了一套时间日期API
B:
LocalDate获取年月日
LocalTime获取时分秒
LocalDateTime获取年月日时分秒
C: 获取对象的方法:
方式1通过静态方法 now();
例如:LocalDateTime ldt = LocalDateTime.now();
方式2通过静态方法of()方法参数可以设置年月日时分秒
例如:LocalDateTime of = LocalDateTime.of(2018, 12, 30, 20, 20, 20);
package org.westos.demo;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
public class MyTest {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println(now);
System.out.println("==================");
LocalTime now1 = LocalTime.now();
System.out.println(now1);
System.out.println("=========");
LocalDateTime now2 = LocalDateTime.now();
System.out.println(now2);
System.out.println("=========");
LocalDate of = LocalDate.of(1000, 10, 10);
System.out.println(of);
System.out.println("============");
LocalTime of1 = LocalTime.of(1, 1, 1, 1);
System.out.println(of1);
LocalDateTime of2 = LocalDateTime.of(2000, 2, 2, 2, 2, 2);
System.out.println(of2);
}
}
2.获取的方法
与获取相关的方法:get系类的方法
ldt.getYear();获取年
ldt.getMinute();获取分钟
ldt.getHour();获取小时
getDayOfMonth 获得月份天数(1-31)
getDayOfYear 获得年份天数(1-366)
getDayOfWeek 获得星期几(返回一个 DayOfWeek枚举值)
getMonth 获得月份, 返回一个 Month 枚举值
getMonthValue 获得月份(1-12)
getYear 获得年份
package org.westos.demo;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
public class MyTest2 {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
int year = now.getYear();
System.out.println(year);
System.out.println("================");
Month month = now.getMonth();
System.out.println(month);
System.out.println("=================");
int monthValue = now.getMonthValue();
System.out.println(monthValue);
System.out.println("=================");
int dayOfMonth = now.getDayOfMonth();
System.out.println(dayOfMonth);
System.out.println("=================");
DayOfWeek dayOfWeek = now.getDayOfWeek();
System.out.println(dayOfWeek);
System.out.println("=================");
int dayOfYear = now.getDayOfYear();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.println(dayOfYear);
System.out.println(hour);
System.out.println(minute);
System.out.println(second);
}
}
3.格式化日期:DateTimeFormatter类
package org.westos.demo;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class MyTest3 {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String str = dateTimeFormatter.format(now);
System.out.println(str);
System.out.println("===========");
LocalDate now1 = LocalDate.now();
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String format = dateTimeFormatter1.format(now1);
System.out.println(format);
System.out.println("=============");
LocalTime now2 = LocalTime.now();
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("HH时mm分ss秒");
String format1 = dateTimeFormatter2.format(now2);
System.out.println(format1);
}
}
4.转换
转换的方法 toLocalDate();toLocalTime();
例如:LocalDate localDate = ldt.toLocalDate();
例如:LocalTime localTime = ldt.toLocalTime();
package org.westos.demo;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class MyTest4 {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
LocalDate localDate = now.toLocalDate();
System.out.println(localDate);
LocalTime localTime = now.toLocalTime();
System.out.println(localTime);
}
}
5.判断的方法
isAfter()判断一个日期是否在指定日期之后
isBefore()判断一个日期是否在指定日期之前
isEqual(); 判断两个日期是否相同
isLeapYear()判断是否是闰年注意是LocalDate类中的方法
例如: boolean after = ldt.isAfter(LocalDateTime.of(2024, 1, 1, 2, 3));
例如 boolean b= LocalDate.now().isLeapYear();
package org.westos.demo;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class MyTest5 {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
LocalDate of = LocalDate.of(1, 1, 1);
boolean b = now.isAfter(of);
System.out.println(b);
System.out.println("=========");
boolean before = now.isBefore(of);
System.out.println(before);
System.out.println("============");
boolean equal = now.isEqual(of);
System.out.println(equal);
System.out.println("=======");
boolean leapYear = now.isLeapYear();
System.out.println(leapYear);
}
}
6.解析日期字符串
解析日期:把日期字符串转换成日期对象
解析的静态方法parse("2007-12-03T10:15:30");
paser() 将一个日期字符串解析成日期对象,注意字符串日期的写法的格式要正确,否则解析失败
例如:LocalDateTime parse = LocalDateTime.parse("2007-12-03T10:15:30");
按照我们指定的格式去解析:
注意细节:如果用LocalDateTime 想按照我们的自定义的格式去解析,注意
日期字符串的 年月日时分秒要写全,不然就报错
LocalDateTime ldt4 = LocalDateTime.now();
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime.parse("2018-01-21 20:30:36", formatter2);
package org.westos.demo;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
public class MyTest6 {
public static void main(String[] args) {
String str="1936-12-12";
LocalDate parse = LocalDate.parse(str);
System.out.println(parse);
System.out.println("==================");
String time="12:12:12";
LocalTime parse1 = LocalTime.parse(time);
System.out.println(parse1);
System.out.println("==================");
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
String s="2020-06-19T18:43:37";
LocalDateTime parse2 = LocalDateTime.parse(s);
System.out.println(parse2);
System.out.println("=================");
String s2="2020-06-19 18:43:37";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse3 = LocalDateTime.parse(s2, dateTimeFormatter);
System.out.println(parse3);
}
}
7.加减时间的方法
添加年月日时分秒的方法 plus系列的方法 都会返回一个新的LocalDateTime的对象
LocalDateTime localDateTime = ldt.plusYears(1);
LocalDateTime localDateTime1 = ldt.plusMonths(3);
LocalDateTime localDateTime2=ldt.plusHours(10);
减去年月日时分秒的方法 minus 系列的方法 注意都会返回一个新的LocalDateTime的对象
例如:LocalDateTime localDateTime2 = ldt.minusYears(8);
package org.westos.demo;
import java.time.LocalDate;
public class MyTest7 {
public static void main(String[] args) {
String s="2020-10-10";
LocalDate parse = LocalDate.parse(s);
System.out.println(parse);
LocalDate localDate = parse.plusYears(2);
System.out.println(localDate);
System.out.println(parse);
LocalDate localDate1 = localDate.plusMonths(2);
System.out.println(localDate1);
System.out.println("===============");
LocalDate now = LocalDate.now();
System.out.println(now);
LocalDate localDate2 = now.minusYears(2);
System.out.println(localDate2);
LocalDate localDate3 = now.minusMonths(2);
System.out.println(localDate3);
}
}
8.with指定日期时间
指定年月日时分秒的方法 with系列的方法 注意都会返回一个新的LocalDateTime的对象
例如 LocalDateTime localDateTime3 = ldt.withYear(1998);
//获取这个月的第几个星期几是几号,比如 TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY) 代表的意思是这个月的第二个星期五是几号
// TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY)
LocalDateTime with1 = now.with(TemporalAdjusters.dayOfWeekInMonth(2,DayOfWeek.FRIDAY));
package org.westos.demo;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
public class MyTest8 {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
LocalDateTime localDateTime = now.withYear(1000);
System.out.println(localDateTime);
System.out.println(now.withMonth(2));
System.out.println(now.withDayOfMonth(22));
System.out.println("=====================");
LocalDate now1 = LocalDate.now();
System.out.println(now1);
TemporalAdjuster next = TemporalAdjusters.next(DayOfWeek.MONDAY);
LocalDate with = now1.with(next);
System.out.println(with);
System.out.println("========================");
TemporalAdjuster next1 = TemporalAdjusters.next(DayOfWeek.FRIDAY);
LocalDate with1 = now1.with(next1);
System.out.println(with1);
System.out.println("========================");
TemporalAdjuster temporalAdjuster = TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY);
LocalDate with2 = now1.with(temporalAdjuster);
System.out.println(with2);
System.out.println("========================");
TemporalAdjuster temporalAdjuster1 = TemporalAdjusters.firstDayOfMonth();
System.out.println(temporalAdjuster1);
LocalDate with3 = now1.with(temporalAdjuster1);
System.out.println(with3);
System.out.println("========================");
TemporalAdjuster temporalAdjuster3 = TemporalAdjusters.dayOfWeekInMonth(4, DayOfWeek.FRIDAY);
LocalDate with4 = now1.with(temporalAdjuster3);
System.out.println(with4);
}
}
二.时间戳类
1.概述
Instant 时间戳类从1970-01-01 00:00:00 截止到当前时间的毫秒值
1获取对象的静态方法 now()
注意默认获取出来的是当前的美国时间和我们相差八个小时
Instant ins = Instant.now();
System.out.println(ins);
我们在东八区 所以可以加8个小时 就是我们的北京时间
2. Instant中设置偏移量的方法:atOffset() 设置偏移量
OffsetDateTime time = ins.atOffset(ZoneOffset.ofHours(8));
System.out.println(time);
3.获取系统默认时区时间的方法atZone()
方法的参数是要一个时区的编号可以通过时区编号类获取出来
ZoneId.systemDefault()获取本地的默认时区ID
ZonedDateTime zonedDateTime = ins.atZone(ZoneId.systemDefault());
System.out.println(zonedDateTime);
4.get系列的方法
getEpochSecond() 获取从1970-01-01 00:00:00到当前时间的秒值
toEpochMilli();获取从1970-01-01 00:00:00到当前时间的毫秒值
getNano()方法是把获取到的当前时间的秒数 换算成纳秒
long epochSecond = ins.getEpochSecond();//获取从1970-01-01 00:00:00到当前时间的秒值
getNano()方法是把获取到的当前时间的豪秒数 换算成纳秒 比如当前时间是2018-01-01 14:00:20:30
那就把30豪秒换算成纳秒 int nano = ins.getNano();
5. ofEpochSecond()方法 给计算机元年增加秒数
ofEpochMilli() 给计算机元年增加毫秒数
例如 Instant instant = Instant.ofEpochSecond(5);
System.out.println(instant);
单位换算
0.1 毫秒 = 10 的5次方纳秒 = 100000 纳秒
1 毫秒 = 1000 微妙 = 1000000 纳秒
2.获取方法
getEpochSecond() 获取从1970-01-01 00:00:00到当前时间的秒值
toEpochMilli();获取从1970-01-01 00:00:00到当前时间的毫秒值
getNano()方法是把获取到的当前时间的秒数 换算成纳秒
long epochSecond = ins.getEpochSecond();//获取从1970-01-01 00:00:00到当前时间的秒值
getNano()方法是把获取到的当前时间的豪秒数 换算成纳秒 比如当前时间是2018-01-01 14:00:20:30
那就把30豪秒换算成纳秒 int nano = ins.getNano();
package org.westos.demo2;
import java.time.Instant;
public class MyTest {
public static void main(String[] args) {
long l = System.currentTimeMillis();
System.out.println(l);
Instant now = Instant.now();
System.out.println(now);
long l1 = now.toEpochMilli();
System.out.println(l1);
System.out.println("=====================");
System.out.println(l1/1000);
long epochSecond = now.getEpochSecond();
System.out.println(epochSecond);
}
}
3.设置偏移量
Instant中设置偏移量的方法:atOffset() 设置偏移量
OffsetDateTime time = ins.atOffset(ZoneOffset.ofHours(8));
System.out.println(time);
package org.westos.demo2;
import java.time.*;
public class MyTest2 {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println(now);
OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);
}
}
三.世界时区类
ZoneId 时间时区类
方法的参数是要一个时区的编号可以通过时区编号类获取出来
//ZoneId.systemDefault()获取本地的默认时区ID
ZonedDateTime zonedDateTime = ins.atZone(ZoneId.systemDefault());
System.out.println(zonedDateTime);
ofEpochSecond()方法 给计算机元年增加秒数
ofEpochMilli() 给计算机元年增加毫秒数
例如 Instant instant = Instant.ofEpochSecond(5);
System.out.println(instant);
单位换算
0.1 毫秒 = 10 的5次方纳秒 = 100000 纳秒
1 毫秒 = 1000 微妙 = 1000000 纳秒
1.获取世界各个地方的时区的集合 的方法getAvailableZoneIds()
? 使用ZoneID中的静态方法getAvailableZoneIds();来获取
? 例如:Set availableZoneIds = ZoneId.getAvailableZoneIds();
2.获取系统默认时区的ID
? ZoneId zoneId = ZoneId.systemDefault(); //Asia/Shanghai
3.获取带有时区的日期时间对象
? //创建日期对象
LocalDateTime now = LocalDateTime.now();
//获取不同国家的日期时间根据各个地区的时区ID名创建对象
ZoneId timeID = ZoneId.of("Asia/Shanghai");
//根据时区ID获取带有时区的日期时间对象
ZonedDateTime time = now.atZone(timeID);
System.out.println(time);
//方式2 通过时区ID 获取日期对象
LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(now2);
package org.westos.demo2;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Set;
public class MyTest3 {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId);
System.out.println("===========================");
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
for (String availableZoneId : availableZoneIds) {
System.out.println(availableZoneId);
}
System.out.println("===========================");
ZoneId id = ZoneId.of("Africa/Monrovia");
LocalDateTime now = LocalDateTime.now(id);
System.out.println(now);
System.out.println("=============================");
LocalDateTime now1 = LocalDateTime.now();
System.out.println(now1);
LocalDateTime now2 = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(now2);
ZoneId id2 = ZoneId.of("Asia/Shanghai");
LocalDateTime now3 = LocalDateTime.now(id2);
System.out.println(now3);
System.out.println("=============================");
Instant now4 = Instant.now();
System.out.println(now4);
Instant instant = Instant.ofEpochSecond(1000);
System.out.println(instant);
Instant instant1 = Instant.ofEpochMilli(1);
System.out.println(instant1);
}
}
四.Duration和Period类
Duration:
用于计算两个“时间”间隔的类
Period:
用于计算两个“日期”间隔的类
Duration类中静态方法between()
Instant start = Instant.now();
for(int i=0;i<1000L;i++){
System.out.println("循环内容");
}
Instant end = Instant.now();
静态方法:between() 计算两个时间的间隔,默认是秒
Duration between = Durati’on.between(start, end);
Duration中的toMillis()方法:将秒转成毫秒
System.out.println(between.toMillis());
Period类 中的静态方法between()
计算两个日期之间的间隔
LocalDate s = LocalDate.of(1985, 03, 05);
LocalDate now = LocalDate.now();
Period be = Period.between(s, now);
System.out.println(be.getYears());间隔了多少年
System.out.println(be.getMonths());间隔了多少月
System.out.println(be.getDays());间隔多少天
package org.westos.demo2;
import java.time.Duration;
import java.time.Instant;
public class MyTest4 {
public static void main(String[] args) {
Instant start = Instant.now();
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
Instant end = Instant.now();
Duration between = Duration.between(start, end);
System.out.println(between);
long days = between.toDays();
long hours = between.toHours();
long minutes = between.toMinutes();
long millis = between.toMillis();
System.out.println(millis+"毫秒");
System.out.println(days);
System.out.println(hours);
System.out.println(minutes);
}
}
package org.westos.demo2;
import java.time.LocalDate;
import java.time.Period;
public class MyTest5 {
public static void main(String[] args) {
LocalDate day1 = LocalDate.of(1000, 10, 10);
LocalDate day2 = LocalDate.now();
Period between = Period.between(day1, day2);
System.out.println(between);
System.out.println(between.getDays());
System.out.println(between.getMonths());
System.out.println(between.getYears());
}
}
五.时间校正器
TemporalAdjuster : 时间校正器,是个接口,
一般我们用该接口的一个对应的工具类 TemporalAdjusters中的一些常量,来指定日期
例如:
LocalDate now = LocalDate.now();
System.out.println(now);
1 使用TemporalAdjusters自带的常量来设置日期
LocalDate with = now.with(TemporalAdjusters.lastDayOfYear());
System.out.println(with);
2 采用TemporalAdjusters中的next方法来指定日期
LocalDate date = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println(date);
例如:TemporalAdjusters.next(DayOfWeek.SUNDAY) 本周的星期天
例如:TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY) 下一周的星期一
3 采用自定义的方式来指定日期 比如指定下个工作日
LocalDateTime ldt = LocalDateTime.now();
LocalDateTime workDay = ldt.with(new TemporalAdjuster() {
@Override
public Temporal adjustInto(Temporal temporal) {
//向下转型
LocalDateTime ld = (LocalDateTime) temporal;
//获取这周的星期几
DayOfWeek dayOfWeek = ld.getDayOfWeek();
if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
return ld.plusDays(3);//如果这天是星期五,那下个工做日就加3天
} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
return ld.plusDays(2);//如果这天是星期六,那下个工做日就加2天
} else {
//其他就加一天
return ld.plusDays(1);
}
}
});
System.out.println(workDay);
package org.westos.demo3;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
public class MyTest {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
TemporalAdjuster temporalAdjuster = TemporalAdjusters.firstDayOfMonth();
TemporalAdjuster temporalAdjuster1 = TemporalAdjusters.lastDayOfYear();
LocalDateTime with = now.with(temporalAdjuster);
LocalDateTime with1 = now.with(temporalAdjuster1);
System.out.println(with1);
System.out.println(with);
System.out.println("========================");
LocalDate now1 = LocalDate.now();
LocalDate with2 = now1.with(new TemporalAdjuster() {
@Override
public Temporal adjustInto(Temporal temporal) {
LocalDate localDate = (LocalDate) temporal;
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
LocalDate localDate1 = localDate.plusDays(3);
return localDate1;
} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
LocalDate localDate1 = localDate.plusDays(2);
return localDate1;
} else {
LocalDate localDate1 = localDate.plusDays(1);
return localDate1;
}
}
});
System.out.println(with2);
}
}
六.DateTimeFormatter
DateTimeFormatter JDK1.8 提供的格式化日期的类
1.获取对象的方式,通过静态方法ofPattern("yyyy-MM-dd");
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime now = LocalDateTime.now();
2.format()方法把一个日期对象的默认格式 格式化成指定的格式
String format1 = dateFormat.format(now);
System.out.println(format1);
3.格式化日期 方式2使用日期类中的format方法 传入一个日期格式化类对象
LocalDateTime now1 = LocalDateTime.now();
使用日期类中的format方法 传入一个日期格式化类对象
使用DateTimeFormatter中提供好的日期格式常量
now1.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
4.使用自定义的日期格式格式化字符串
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//自定义一个日期格式
String time = now1.format(timeFormat);
System.out.println(time);
5. 把一个日期字符串转成日期对象
使用日期类中的parse方法传入一个日期字符串,传入对应的日期格式化类
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime parse = LocalDateTime.parse(time, timeFormat);
System.out.println(parse);
package org.westos.demo3;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class MyTest2 {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String format = dateTimeFormatter.format(now);
System.out.println(format);
System.out.println("===============");
String format1 = now.format(dateTimeFormatter);
System.out.println(format1);
}
}
七.带时区的时间或日期
ZonedDate,ZonedTime、ZonedDateTime : 带时区的时间或日期
用法和 LocalDate、 LocalTime、 LocalDateTime 一样 只不过ZonedDate,ZonedTime、ZonedDateTime 这三个带有当前系统的默认时区
package org.westos.demo3;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
public class MyTest3 {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now);
LocalDateTime now1 = LocalDateTime.now();
System.out.println(now1);
}
}