LocalDateTime\LocalDate\LocalTime
1.jdk1.8+
2.Date和Calendar类都在java.util包下,新日期类在java.time包下
3.内部有一个私有的有参构造,不能new对象
4.常用方法
1.now():获取当前时间
2.of(int year, Month month, int dayOfMonth, int Hour, int minute, int second):根据指定日期创建对象
3.一系列getter方法:用于获取日期相关字段值
4.提供了一系列plus方法:用于计算日期,每次计算都会返回一个新的对象,不会修改原来的对象
5.format(DateTimeFormatter formatter):日期对象格式化为字符串
DateTimeFormatter
1.jdk1.8+
2.DateFormat 和 SimpleDateFormat 都在java.text包下. DateTimeFormatter在java.time.format包下
3.常用方法
1.ofPattern(String pattern):根据指定格式化样式创建格式化器对象
2.format(TemporalAccessor temporal):格式化指定日期对象
4.LocalDateTime 和 Date 之间的转换
补充类:Instant
1.jdk1.8+
2.瞬时类,时间戳,时刻类
3.Date --> LocalDateTime
4.LocalDateTime --> Date
public class Demo01LocalDateTime {
@Test
public void test01(){
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
LocalDateTime ldt = LocalDateTime.of(2019, 12, 12, 10, 33, 30);
System.out.println(ldt);
System.out.println(ldt.getYear());
System.out.println(ldt.getMonth().getValue());
System.out.println(ldt.getDayOfMonth());
System.out.println(ldt.getDayOfWeek().getValue());
System.out.println(ldt.getDayOfYear());
LocalDateTime newLdt = ldt.plusDays(7);
System.out.println(newLdt);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
String nowStr1 = now.format(dtf);
System.out.println(nowStr1);
String nowStr = dtf.format(now);
System.out.println(nowStr);
}
@Test
public void test02(){
// date --> localdatetime
Date date = new Date();
Instant instant = date.toInstant();
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(localDateTime);
}
@Test
public void test03(){
// localdatetime --> date
LocalDateTime now = LocalDateTime.now();
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
System.out.println(date);
}
}
自定义日期工具类
package org.jgs1904.util;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* @ClassName MyDateUtil
* @Description 自定义日期工具类
* @Author RenYuWen
* @Since 2019/12/12 10:05
*/
public final class MyDateUtil {
private MyDateUtil(){}
/**
* @Description: Date 转 LocalDateTime
* @param: [date] Date对象
* @return: java.time.LocalDateTime LocalDateTime对象
* @author: RenYuWen
* @date: 2019/12/12 10:10
*/
public static LocalDateTime dateToLocalDateTime(Date date){
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
return localDateTime;
}
/**
* @Description: LocalDateTime 转 Date
* @param: [localDateTime] LocalDateTime 对象
* @return: java.util.Date Date 对象
* @author: RenYuWen
* @date: 2019/12/12 10:11
*/
public static Date LocalDateTimeToDate(LocalDateTime localDateTime){
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
return date;
}
}