1 Calendar日历类
* 可以针对于日期中的每一个日期项,进行操作
* 年, 月, 日, 时,分, 秒,毫秒,星期
* Calendar对象创建
Calendar time = Calendar.getInstance(); //默认表示当前系统时间
* Calendar对象与Date对象之间的转换
//Date --> Calendar
Calendar time = Calendar.getInstance();
time.setTime(Date date) ;// 设置一个新的日期,表示date对应的Calendar形式
//Calendar --> date
Date date = time.getTime();
* Calendar对象的常用方法
Calendar time = Calendar.getInstance();
//针对于某一个日期项进行设置
time.set(Calendar.DAY_OF_MONTH,10) ;
time.get(Calendar.DAY_OF_MONTH);
time.add(Calendar.DAY_OF_MONTH,100) ;
time1.before(time2) ;
time1.after(time2) ;
2 jdk新日期类
-
LocalDate , LocalTime , LocalDateTime
-
DateTimeFormatter
-
Period , Duration , ChronoUnit
-
ZoneId
-
Instant, ZoneDateTime (新老日期转化)
2.1 新日期的创建
-
LocalDate , LocalTime , LocalDateTime 表示日期时间
-
LocalDateTime.now(); //获得当前系统时间的日期对象 LocalDateTime.of(); //获得指定时间的日期对象
2.2 获得日期信息
LocalDateTime today = LocalDateTime.now();
today.get系列(); //获得不同的日期项
2.3 日期格式处理
//LocalDateTime默认的日期格式 yyyy-MM-ddTHH:mm:ss
LocalDateTime day = LocalDateTime.parse("1982/02/23 03:03:03");
System.out.println(day);
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime day2 = LocalDateTime.parse("1982/02/23 03:03:03",format);
System.out.println( day2.format(format) );
2.4 日期的计算
一个日期加减数字
LocalDate day = LocalDate.of(1987, 2, 23);
// LocalDate r = day.plus(3, ChronoUnit.DAYS);
// LocalDate r = day.plusDays(10);
LocalDate r = day.minus(1,ChronoUnit.MONTHS);
System.out.println(r);
Period p = Period.of(0, 1, 15);
LocalDate r = day.plus(p);
两个日期间隔
//间隔时间较长, 以年月日为间隔单位
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1987,2,23);
Period p = Period.between(birthday,today);
System.out.println(p);
System.out.println(p.getYears());
long days = ChronoUnit.YEARS.between(birthday, today);
System.out.println(days);
//间隔时间较短,以时分秒为单位
LocalDateTime today = LocalDateTime.now();
LocalDateTime birthday = LocalDateTime.of(1987,2,23,3,3,3);
Duration between = Duration.between(birthday, today);
System.out.println(between.toDays());
2.5 新老日期类转化
-
需要Instant , ZoneDateTime , ZoneId 配合完成
//Date ---> LocalDateTime
Date date = new Date();
Instant instant = date.toInstant();
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
LocalDateTime day = zonedDateTime.toLocalDateTime();
System.out.println(day);
//LocalDateTime ---> Date
LocalDateTime birthday = LocalDateTime.of(1987, 2, 23, 3, 3, 3);
ZonedDateTime zonedDateTime = birthday.atZone(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
Date date = Date.from(instant);
System.out.println(date);
那么今天的内容就到这里啦,如果存在哪些疑问或问题欢迎大家指出,我们下期再见~
标签:Java,日期,LocalDateTime,Date,20,Calendar,LocalDate,day From: https://blog.csdn.net/a2018204587/article/details/144155604