侧边栏壁纸
博主头像
小吴同学博主等级

去学习,去读书,去受教育,去看山川河流,去远方!!!

  • 累计撰写 15 篇文章
  • 累计创建 9 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

JDK1.8 日期时间相关API学习文档

小吴同学
2023-05-18 / 0 评论 / 14 点赞 / 2,047 阅读 / 2,183 字

LocalDate、 LocalTime、 LocalDateTime类的实例是不可变的对象,LocalDate 表示年月日 LocalTime 表示时分秒 LocalDateTime 表示年月日时分秒。

常用方法

1.获取对象的方法
      // 获取对象
      LocalDate now = LocalDate.now(); // 获取当前的年月日
      System.out.println(now);
        
      LocalTime now1 = LocalTime.now(); // 获取当前的时分秒
      System.out.println(now1);
        
      LocalDateTime now2 = LocalDateTime.now(); // 年月日时分秒 
      System.out.println(now2);

输出示例:

2023-05-18
10:39:22.625
2023-05-18T10:39:22.625

2、返回指定日期对象

将返回一个LocalDate与指定的年,月和日。 该日期必须在年和月中有效,否则将抛出异常。

        // 返回的是指定日期的年月日对象
        LocalDate of = LocalDate.of(2023, 05, 18);
        System.out.println(of);
        // 返回的是指定后的日期时分秒对象
        LocalTime of1 = LocalTime.of(14, 20, 30);
        System.out.println(of1);
        // 返回的是指定日期的年月日时分秒对象
        LocalDateTime of2 = LocalDateTime.of(2010, 10, 20, 14, 30, 30);
        System.out.println(of2);

输出示例:

2023-05-18
14:20:30
2010-10-20T14:30:30

3、与获取相关的方法:get系类的方法
LocalDateTime now = LocalDateTime.now();
// 获取当前时间 年份
int year = now.getYear();
// 获取当前时间 月的英文缩写
Month month = now.getMonth();
// 获取当前时间 月份
int monthValue = now.getMonthValue(); 
// 获取当前时间 日
int dayOfMonth = now.getDayOfMonth();
// 获取当前时间的星期
DayOfWeek dayOfWeek = now.getDayOfWeek();
//获取当前时间是今年的第几天
int dayOfYear = now.getDayOfYear();
// 获取当前时间的小时
int hour = now.getHour();
// 获取当前时间的分钟
int minute = now.getMinute();
// 获取当前时间的秒
int second = now.getSecond();
System.out.println(year);
System.out.println(month); 
System.out.println(monthValue);
System.out.println(dayOfMonth);
System.out.println(dayOfWeek); 
System.out.println(dayOfYear);
System.out.println(hour);
System.out.println(minute);
System.out.println(second);

输出示例:

2023
MAY
5
18
THURSDAY
138
10
56
0

4、格式化日期日期字符串的方法 format()
// 格式化日期日期字符串的方法 format ()
LocalDate now = LocalDate.now();
// 默认格式 2023-05-18 
System.out.println(now.toString());
// JDK1.8 格式化日期的类 DateTimeFormatter 指定格式 String yyyy = now.format(DateTimeFormatter.ofPattern("yyyy"))
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String dateStr = now.format(formatter);
System.out.println(dateStr);


LocalDateTime now1 = LocalDateTime.now();
// 默认格式 2023-05-18T11:06:32.236
System.out.println(now1.toString());
//把日期对象,格式化成日期字符串
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
String str = now1.format(formatter2);
System.out.println(str);

输出示例:

2023-05-18
2023年05月18日
2023-05-18T11:06:32.236
2023年05月18日 11点06分32秒

5、转换的方法 toLocalDate();toLocalTime();
// 获取当前时间年月日时分秒
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 转换为年月日
LocalDate localDate = now.toLocalDate();
System.out.println(localDate);
// 转换为时分秒
LocalTime localTime = now.toLocalTime();
System.out.println(localTime);

输出示例:

2023-05-18T11:12:22.212
2023-05-18
11:12:22.212

6、常见判断方法
LocalDate now = LocalDate.now();
LocalDate of = LocalDate.of(2000, 12, 12);
// isAfter() 判断一个日期(当前日期)是否在指定日期之后
boolean after = now.isAfter(of);
System.out.println(after);
// isBefore() 判断一个日期是否在指定日期之前
boolean before = now.isBefore(of);
System.out.println(before);
// 判断两个日期是否相同
boolean equal = now.isEqual(of);
System.out.println(equal);
boolean equal1 = of.isEqual(of);
System.out.println(equal1);
//判断是不是闰年
boolean leapYear = now.isLeapYear();
System.out.println(leapYear);

输出示例:

true
false
false
true
false

7、解析的静态方法parse

paser() 将一个日期字符串解析成日期对象,注意字符串日期的写法的格式要正确,否则解析失败

        // 解析的静态方法parse("2007-12-03T10:15:30");把一个日期字符串解析成日期对象
        String dateStr = "2007-12-03";
        // 按照默认格式来解析
        LocalDate parse = LocalDate.parse(dateStr);
        System.out.println(parse);
        String dateStr2 = "2007年12月03日";
        // 按照指定格式来解析
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        LocalDate parse2 = LocalDate.parse(dateStr2, formatter);
        System.out.println(parse2);
        String dateStr3 = "2021年10月05日 14点20分30秒";
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
        LocalDateTime parse1 = LocalDateTime.parse(dateStr3, formatter2);
        System.out.println(parse1);

输出示例:

2007-12-03
2007-12-03
2021-10-05T14:20:30

8、添加年月日时分秒和删除年月日方法
/**
 * 减去输入年份到年份字段 
 * 检查结果日期是否无效 
 * 如果有必要,将月份调整到最后一个有效日期 
 */
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 增加年月日时分秒调用 plusXXX系列的方法 都会返回一个新的LocalDateTime的对象
LocalDateTime localDateTime = now.plusYears(2);
System.out.println(localDateTime);

//减去年月日时分秒的方法 minusXXX 系列的方法 注意都会返回一个新的LocalDateTime的对象
LocalDateTime localDateTime1 = now.minusYears(3);
System.out.println(localDateTime1);

输出示例:

2023-05-18T11:43:37.445
2025-05-18T11:43:37.445
2020-05-18T11:43:37.445

9、指定年月日时分秒的方法
// 指定年月日时分秒的方法 with系列的方法 注意都会返回一个新的LocalDateTime的对象
LocalDate now=LocalDate.now();
// 这个月的第2个星期五是几月几号
LocalDateTime with = now.with(TemporalAdjusters.dayOfWeekInMonth(4,DayOfWeek.FRIDAY)).atStartOfDay();
System.out.println(with);

输出示例:

2023-05-26T00:00

10、Instant 时间戳类从1970-01-01 00:00:00 截止到当前时间的毫秒值
// Instant 时间戳类从1970 -01 - 01 00:00:00 截止到当前时间的毫秒值 美国时间
Instant now = Instant.now();
System.out.println(now.toString());
// 设置时间的偏移量 提前8小时
OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);
// 设置时区 东八区
ZonedDateTime zonedDateTime = now.atZone(ZoneId.systemDefault());
System.out.println(zonedDateTime);
Instant now2 = Instant.now();
//获取1970 -01 - 01 00:00:00 截止到当前时间的毫秒值
long l = now2.toEpochMilli();
//获取1970 -01 - 01 00:00:00 截止到当前时间的秒值
long epochSecond = now2.getEpochSecond();
System.out.println(l / 1000);
System.out.println(epochSecond);
//给计算机元年添加相应的毫秒值
Instant instant = Instant.ofEpochMilli(1000 * 60 * 60 * 24);
System.out.println(instant);
//给计算机元年添加相应的秒值
Instant instant2 = Instant.ofEpochSecond(60 * 60 * 24 * 2);
System.out.println(instant2);

输出示例:

2023-05-18T05:58:00.092Z
2023-05-18T13:58:00.092+08:00
2023-05-18T13:58:00.092+08:00[Asia/Shanghai]
1684389480
1684389480
1970-01-02T00:00:00Z
1970-01-03T00:00:00Z

11、Duration : 用于计算两个“时间”间隔的类
// 记录一下开始的时间戳
Instant now = Instant.now();
for (int i = 0; i < 5000; i++) {
    System.out.println(i);
}
// 记录一下结束的时间戳
Instant end = Instant.now();
// Duration:用于计算两个"时间”间隔的类
Duration between = Duration.between(now, end);
// long seconds = between.getSeconds() 间隔的秒值
long l = between.toMillis();
// long l1 = between.toDays()间隔天数
// long l2 = between.toMinutes()间隔分钟
System.out.println("耗时:" + l + "毫秒");

输出示例:

0

1

耗时:42毫秒

12、Period : 用于计算两个“日期”间隔的类
LocalDate birthday = LocalDate.of(1985, 4, 10);
LocalDate now = LocalDate.now();
//Period:用于计算两个“日期”间隔的类
Period between = Period.between(birthday, now);
int years = between.getYears();
int months = between.getMonths();
int days = between.getDays();
System.out.println(years);
System.out.println(months);
System.out.println(days);

输出示例:

38
1
8

13、TemporalAdjuster : 时间校正器
         /**
         * 我要获取下个工作日的日期
         * 如果当前是星期五 下个工作日 加3天
         * 如果当前是星期六 下个工作日 加2天
         * 如果是其他星期 下个工作日 加1天
         */
        LocalDate now = LocalDate.now();
        LocalDate date = now.with(new TemporalAdjuster() {
            @Override
            public Temporal adjustInto(Temporal temporal) {
                // 传过来的这个参数,就是当前的日期
                LocalDate mydate = (LocalDate) temporal;
                // 获取当前的星期
                DayOfWeek dayOfWeek = mydate.getDayOfWeek();
                if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
                    return mydate.plusDays(3);
                } else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
                    return mydate.plusDays(2);
                } else {
                    return mydate.plusDays(1);
                }
            }
        });

        System.out.println(date);

输出示例:

2023-05-19

14、DateTimeFormatter :解析和格式化日期或时间的类
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);
   
14

评论区