JDK8之前日期时间API:
- System中的currentTimeMillis
//返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差
//常用于订单号的唯一性,如果颗粒度极小的话再加几位随机数以保证其唯一性。
long time = System.currentTimeMillis();
System.out.println(time);//1618910317178
两个Date类:
java.util.Date和java.sql.Date
- 两个构造器的使用
- 构造器1:Date() 创建一个当前时间的date对象
- 构造器2:Date(long mills) 创建一个指定毫秒数的date对象
- 两个方法的使用
- 》toString:显示当前的年,月,日,时,分,秒
- 》getTime:获取当前Date对象对应的毫秒数(时间戳)
- java.sql.Date 对应数据库中的日期类型的变量:
- 》如何实例化
- 》如何将java.util.Date对象转化为java.sql.Date对象
//构造器1:Date() 创建一个当前时间的date对象
Date date1 = new Date();
System.out.println(date1.toString());
System.out.println(date1.getTime());
//构造器2:Date(long mills) 创建一个指定毫秒数的date对象
Date date2 = new Date(1618911161534l);
System.out.println(date2.toString());
//如何实例化java.sql.Date
java.sql.Date date3 = new java.sql.Date(35235325245L);
System.out.println(date3);
//如何将java.util.Date对象转化为java.sql.Date对象
Date date4 = new Date();
java.sql.Date date5 = new java.sql.Date(date4.getTime());
SimpleDateFormat:
/**
* 两个操作:
* 1.格式化:日期-》字符串
* 2.解析:字符串-》日期
*/
@Test
public void SimpleDateFormatTest() throws ParseException {
//实例化使用默认的构造器
SimpleDateFormat sdf = new SimpleDateFormat();
//格式化:日期-》字符串
Date date = new Date();
System.out.println(date);
String format = sdf.format(date);
System.out.println(format);//21-4-25 上午11:19
//解析:字符串-》日期
//String str = "2019-08-01";
String str = "21-4-25 上午11:19";
Date date1 = sdf.parse(str);
System.out.println(date1);
//使用带参数的构造器
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//格式化
String format1 = sdf2.format(date);
System.out.println(format1);//2021-04-26 02:16:53
//解析
Date parse = sdf2.parse("2021-04-26 02:16:53");
System.out.println(parse);//Mon Apr 26 02:16:53 CST 2021
}
/**
* 练习:字符串转为sqlDate
* @throws ParseException
*/
@Test
public void str2SqlDate() throws ParseException {
String birth = "2019-01-11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(birth);
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
System.out.println(sqlDate);
}
/**
* 练习:三天打鱼两天晒网 从1990-01-01 到xxxx-xx-xx
*/
@Test
public void testDay() throws ParseException {
/**
* 方式1:用毫秒数得到总天数,然后用总天数%5.
* 1,2,3为打鱼,45晒网。
*/
String fromDate = "1990-01-01";
String endDate = "2019-12-22";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse(fromDate);
Date date2 = sdf.parse(endDate);
long mills = date2.getTime() - date1.getTime();
long dayMills = (1000 * 60 * 60 * 60 *24);
long days = mills / dayMills + 1;
long res = days % 5;
int i = Integer.parseInt(String.valueOf(res));
switch (i){
case 1:
System.out.println("打鱼");
break;
case 2:
System.out.println("打鱼");
break;
case 3:
System.out.println("打鱼");
break;
case 4:
System.out.println("晒网");
break;
case 5:
System.out.println("晒网");
break;
default:
System.out.println("error");
break;
}
Calendar
@Test
public void testCalendar(){
//1.实例化:
Calendar calendar = Calendar.getInstance();
//2.常用方法:
//get()
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(day); //26
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//116
//set()
calendar.set(Calendar.DAY_OF_MONTH, 22);
day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(day);//22
//add()
calendar.add(Calendar.DAY_OF_MONTH, -1);
day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(day);//21
//getTime()
Date time = calendar.getTime();
System.out.println(time);//Wed Apr 21 14:58:10 CST 2021
//setTime()
Date date = new Date();
calendar.setTime(date);
day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(day);
}
java8的日期时间类
如果我们可以跟别人说:“我们在1502643933071见面,别晚了!”那么就再简单不过了。但是我们希望时间与昼夜和四季有关,于是事情就变复杂了。JDK 1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK 1.1引入Calendar类之后被弃用了。而Calendar并不比Date好多少。它们面临的问题是:
可变性:像日期和时间这样的类应该是不可变的。
偏移性:Date中的年份是从1900开始的,而月份都从0开始。
格式化:格式化只对Date有用,Calendar则不行。
此外,它们也不是线程安全的;不能处理闰秒等。
Java 8 吸收了 Joda-Time 的精华,以一个新的开始为 Java 创建优秀的 API。 新的 java.time 中包含了所有关于本地日期(LocalDate)、本地时间 (LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime) 和持续时间(Duration)的类。历史悠久的 Date 类新增了 toInstant() 方法, 用于把 Date 转换成新的表示形式。这些新增的本地化时间日期 API 大大简 化了日期时间和本地化的管理。
- LocalDate、LocalTime、LocalDateTime 类是其中较重要的几个类,它们的实例是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。
- LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储 生日、纪念日等日期。
- LocalTime表示一个时间,而不是日期。
- LocalDateTime是用来表示日期和时间的,这是一个最常用的类之一。
LocalDate、LocalTime、LocalDateTime的使用
/**
* LocalDate、LocalTime、LocalDateTime的使用
* tips:
* LocalDateTime使用较多
* 三个类的方法大同小异
*/
@Test
public void testLocalXxx(){
//1.实例化:
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);//2021-04-26
System.out.println(localTime);//15:19:09.242
System.out.println(localDateTime);//2021-04-26T15:19:09.242
//of() 设置指定的年月日时分秒,没有偏移量1900
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 11);
System.out.println(localDateTime1); //2020-10-06T13:23:11
//getXxx()
System.out.println(localDateTime.getMonth());//APRIL
System.out.println(localDateTime.getDayOfMonth());//26
System.out.println(localDateTime.getDayOfWeek());//MONDAY
System.out.println(localDateTime.getDayOfYear());//116
System.out.println(localDateTime.getHour());//15
System.out.println(localDateTime.getMinute());//28
System.out.println(localDateTime.getMonthValue());//4
System.out.println(localDateTime.getSecond());//40
System.out.println(localDateTime.getYear());//2021
System.out.println(localDateTime.getNano());//2000000
//with():修改
//与calendar的set()不同,withXxx()体现了不可变性
LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(11);
System.out.println(localDateTime);
System.out.println(localDateTime2);
//plus():添加
LocalDateTime localDateTime3 = localDateTime.plusHours(3);
System.out.println(localDateTime);
System.out.println(localDateTime3);
//minus():减
LocalDateTime localDateTime4 = localDateTime.minusDays(3);
System.out.println(localDateTime);
System.out.println(localDateTime4);
}
Instant(瞬时)
/**
* Instant(瞬时)
* 类似于java.util.Date
*/
@Test
public void testInstant(){
Instant instant = Instant.now();
System.out.println(instant);//2021-04-26T07:43:42.273Z //本初子午线时间
//添加时间偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);//我国可用时间
//返回1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳
System.out.println(instant.toEpochMilli()); //1619423212806
//实例化方式2:
Instant instant1 = Instant.ofEpochMilli(1619423212806L);
System.out.println(instant1); //2021-04-26T07:46:52.806Z
}
DateTimeFormatter
/**
* DateTimeFormatter格式化或解析日期时间
* 类似于SimpleDateFormat
*
* 常用第三种自定义格式
*/
@Test
public void testDateTimeFormatter(){
//1 预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime localDateTime = LocalDateTime.now();
//格式化
String dateTimeStr = formatter.format(localDateTime);
System.out.println(localDateTime);//2021-04-26T15:58:08.216
System.out.println(dateTimeStr);//2021-04-26T15:58:08.216
//解析
TemporalAccessor parse = formatter.parse("2021-04-26T15:58:08.216");
System.out.println(parse);//{},ISO resolved to 2021-04-26T15:58:08.216
//2 本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
String shorts = formatter1.format(localDateTime);
System.out.println(shorts);//21-4-26 下午4:08
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
String longs = formatter2.format(localDateTime);
System.out.println(longs);//2021年4月26日 下午04时08分53秒
DateTimeFormatter formatter4 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
String medium = formatter4.format(localDateTime);
System.out.println(medium);//2021-4-26 16:08:53
DateTimeFormatter formatter5 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
String full = formatter5.format(LocalDate.now());
System.out.println(full);//2021年4月26日 星期一
//3 重点 自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//DateTimeFormatter formatter4 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM); -- 相同
String now = formatter3.format(LocalDateTime.now());
System.out.println(now); //2021-04-26 16:14:53
TemporalAccessor parse1 = formatter3.parse("2021-04-26 16:14:53");
System.out.println(parse1);
}
计算时间间隔的API - Duration 和 Period
Duration - 用于计算两个“时间”间隔,以秒和纳秒为基准
@Test
public void testDuration(){
LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime1 = LocalDateTime.of(2021, 4, 15, 11, 11, 11);
Duration between = Duration.between(localDateTime, localDateTime1);
System.out.println(between);//PT-269H-19M-29.946S
System.out.println(between.getNano());//54000000
System.out.println(between.getSeconds());//-969570
Duration between1 = Duration.between(localDateTime1, localDateTime);
long days = between1.toDays();
System.out.println(days);//11
System.out.println(between1.toHours());//269
System.out.println(between1.toMinutes());//16161
System.out.println(between1.toMillis());//969712361
System.out.println(between1.toString());//PT269H21M52.361S
}
Period:用于计算两个“日期”间隔,以年、月、日衡量
/**
* 只支持LocalDate
*/
@Test
public void testPeriod(){
LocalDate localDate = LocalDate.now();
LocalDate localDate1 = LocalDate.of(2021, 4, 27);
Period between = Period.between(localDate, localDate1);
System.out.println(between);//P1D
System.out.println(between.getYears());//0
System.out.println(between.getMonths());//0
System.out.println(between.getDays());//1
System.out.println(between.getChronology());//ISO
System.out.println(between.getUnits());//[Years, Months, Days]
}
TemporalAdjuster:时间校正器 - 计算时间差
@Test
public void testTemporalAdjuster(){
获取当前日期的下一个周日是哪天?
TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);
//利用LocalDateTime的特性进行修改,将当前日期进行覆盖
LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);
System.out.println(localDateTime);//2021-05-02T16:49:48.436
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
String format = formatter.format(localDateTime);
System.out.println(format);//2021-5-2 16:49:48
// 获取下一个工作日是哪天?
LocalDate localDate = LocalDate.now().with(new TemporalAdjuster() {
@Override
public Temporal adjustInto(Temporal temporal) {
LocalDate localDate = (LocalDate) temporal;
if (localDate.getDayOfWeek().equals(DayOfWeek.FRIDAY)){
return localDate.plusDays(3);
} else if (localDate.getDayOfWeek().equals(DayOfWeek.SATURDAY)){
return localDate.plusDays(2);
} else {
return localDate.plusDays(1);
}
}
});
System.out.println("下一个工作日是"+localDate);
}