Featured image of post 【合集】Java日期时间API:Date、LocalDate、LocalDateTime

【合集】Java日期时间API:Date、LocalDate、LocalDateTime

日期时间声明

1
2
3
4
5
LocalTime localTime = LocalTime.of(0, 0, 0);
LocalDate localDate = LocalDate.of(2014, Month.DECEMBER, 12);
LocalDateTime localDateTim = LocalDateTime.of(2023, 8, 1, 0, 0, 0);
LocalDateTime localDateTime = LocalDateTime.now()
.withYear(2024).withMonth(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);

LocalDateTime、Date互转

1
2
3
4
5
6
7
8
// date 转换为 LocalDateTime
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());

// LocalDate 转换为 Date
Date date = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

// LocalDateTime 转换为 Date
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

字符串 转 DateTime

1
2
3
4
5
LocalTime localTime = LocalTime.parse("01:00:00", DateTimeFormatter.ofPattern("HH:mm:ss"));
LocalDate localDate = LocalDate.parse("2024-05-29", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime localDateTime = LocalDateTime.parse("2024-05-29 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2024-05-29 00:00:00");

DateTime 转 字符串

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
String str = localTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
String str = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String str = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String str = localDateTime.format(DateTimeFormatter.ISO_DATE); // 2023-03-21date
String str = localDateTime.format(DateTimeFormatter.ISO_DATE_TIME); // 2023-03-21T11:06:27.736
String str = localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE); // 2023-03-21
String str = localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); // 2023-03-21T11:08:12.92
String str = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // 2023-03-21 11:06:27
String str = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime); // 同上

SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
String rs = sdf.format(new Date()); // 2023年08月11日 16:09:46 周五 下午
String rs2 = sdf.format(new Date().getTime()); // 2023年08月11日 16:09:46 周五 下午

String str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(1716975154691L);
String str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(1716975154691L));
String str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

获取毫秒值

1
2
3
4
5
// LocalDateTime获取毫秒值
long millisecond1 = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

// Date获取毫秒值
long millisecond2 = date.getTime();

计时器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// 创建并开始计时
Stopwatch stopwatch = Stopwatch.createStarted();
// 计时开始至现在的所用时间,向下取整
log.info("耗费" + stopwatch.elapsed(TimeUnit.SECONDS) + "秒");
// 停止计时
stopwatch.stop();
// 再次计时
stopwatch.start();
// 重置并开始
stopwatch.reset().start();
// 检查是否运行
boolean running = stopwatch.isRunning();

相隔数 注意:同一天相隔0天,其他同理

1
2
3
4
5
long betweenSeconds = ChronoUnit.SECONDS.between(localDateTime1, localDateTime2);
long betweenMinutes = ChronoUnit.MINUTES.between(localDateTime1, localDateTime2);
long betweenDays = ChronoUnit.DAYS.between(localDateTime1, localDateTime2);
long betweenWeeks = ChronoUnit.WEEKS.between(localDateTime1, localDateTime2);
long betweenMonths = ChronoUnit.MONTHS.between(localDateTime1, localDateTime2);

获取指定年、周的开始日、结束日

1
2
3
4
5
6
7
8
9
int year = 2024, week = 20;
  
LocalDate startOfWeek = LocalDate.of(year, 1, 1)
        .plusWeeks(week - 1)
        .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

LocalDate endOfWeek = LocalDate.of(year, 1, 1)
        .plusWeeks(week - 1)
        .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

获取指定年、月的开始日、结束日

1
2
3
4
5
6
int year2 = 2024, month = 5;

LocalDate startOfMonth = LocalDate.of(year2, month, 1);

LocalDate endOfMonth = LocalDate.of(year2, month, 1)
          .with(TemporalAdjusters.lastDayOfMonth());

属于所在年的第几周 2种方式

1
2
int weekOfYear = localDateTime.get(WeekFields.of(DayOfWeek.MONDAY, 4).weekOfYear());
int weekOfYear2 = localDateTime.get(WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear());

所在自然 日/周/月/年 的开始时间、结束时

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// 所在自然日的开始时间、结束时间
LocalDateTime startOfNaturalDay = localDateTime.with(LocalTime.MIN);
LocalDateTime endOfNaturalDay = localDateTime.with(LocalTime.MAX);

// 所在自然周的开始时间、结束时间
LocalDateTime startOfNaturalWeek = localDateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDateTime endOfNaturalWeek = localDateTime.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).with(LocalTime.MAX);

// 所在自然月的开始时间、结束时间
LocalDateTime startOfNaturalMonth = localDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
LocalDateTime endOfNaturalMonth = localDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);

// 所在自然年的开始时间、结束时间
LocalDateTime startOfNaturalYear = localDateTime.with(TemporalAdjusters.firstDayOfYear()).with(LocalTime.MIN);
LocalDateTime endOfNaturalYear = localDateTime.with(TemporalAdjusters.lastDayOfYear()).with(LocalTime.MAX);

getAllDaysBetween两个LocalDate之间的所有日的开始时间、结束时间 包括头尾

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * 两个LocalDate之间的所有日的开始时间、结束时间 包括头尾
 * 输入:
 * 2022, 1, 1
 * 2022, 1, 2
 * 返回:
 * [["2022-01-01T00:00:00","2022-01-01T23:59:59.999999999"],
 * ["2022-01-02T00:00:00","2022-01-02T23:59:59.999999999"]]
 */
@Nonnull
public static List<LocalDateTime[]> getAllDaysBetween(@Nonnull LocalDate startDate,
                                                      @Nonnull LocalDate endDate) {
    List<LocalDateTime[]> days = new ArrayList<>();
    long daysBetween = ChronoUnit.DAYS.between(startDate, endDate) + 1;
    for (long i = 0; i < daysBetween; i++) {
        LocalDateTime currentDayStart = startDate.plusDays(i).atStartOfDay();
        LocalDateTime currentDayEnd = currentDayStart.plusDays(1).minusNanos(1);
        days.add(new LocalDateTime[]{currentDayStart, currentDayEnd});
    }
    return days;
}

getAllMonthsBetween两个LocalDate之间的所有月的开始时间、结束时间 包括头尾

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * 两个LocalDate之间的所有月的开始时间、结束时间 包括头尾
 * 输入:
 * 2022, 1, 1
 * 2022, 2, 1
 * 返回:
 * [["2022-01-01T00:00","2022-01-31T23:59:59.999999999"],
 * ["2022-02-01T00:00","2022-02-28T23:59:59.999999999"]]
 */
@Nonnull
public static List<LocalDateTime[]> getAllMonthsBetween(@Nonnull LocalDate startDate,
                                                        @Nonnull LocalDate endDate) {
    List<LocalDateTime[]> months = new ArrayList<>();
    long monthsBetween = ChronoUnit.MONTHS.between(startDate, endDate) + 1;
    for (long i = 0; i < monthsBetween; i++) {
        LocalDateTime currentMonthStart = startDate.plusMonths(i).withDayOfMonth(1).atStartOfDay();
        LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).minusDays(1).with(LocalTime.MAX);
        months.add(new LocalDateTime[]{currentMonthStart, currentMonthEnd});
    }
    return months;
}

getAllYearsBetween两个LocalDate之间的所有年的开始时间、结束时间 包括头尾

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * 两个LocalDate之间的所有年的开始时间、结束时间 包括头尾
 * 输入:
 * 2022, 1, 1
 * 2023, 1, 1
 * 返回:
 * [["2022-01-01T00:00","2022-12-31T23:59:59.999999999"],
 * ["2023-01-01T00:00","2023-12-31T23:59:59.999999999"]]
 */
@Nonnull
public static List<LocalDateTime[]> getAllYearsBetween(@Nonnull LocalDate startDate,
                                                       @Nonnull LocalDate endDate) {
    List<LocalDateTime[]> years = new ArrayList<>();
    long yearsBetween = ChronoUnit.YEARS.between(startDate, endDate) + 1;
    for (long i = 0; i < yearsBetween; i++) {
        LocalDateTime currentYearStart = startDate.plusYears(i).withDayOfYear(1).atStartOfDay();
        LocalDateTime currentYearEnd = currentYearStart.plusYears(1).minusDays(1).with(LocalTime.MAX);
        years.add(new LocalDateTime[]{currentYearStart, currentYearEnd});
    }
    return years;
}

getStAndEtAnWeek获取第一周不允许跨年,但是最后一周允许跨年的自然周开始时间、结束时间

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * 获取第一周不允许跨年,但是最后一周允许跨年的自然周开始时间、结束时间
 * 输入:2022 1
 * 输出:[2022-01-03T00:00, 2022-01-09T23:59:59.999999999]
 * 输入:2022 52
 * 输出:[2022-12-26T00:00, 2023-01-01T23:59:59.999999999]
 */
@Nonnull
public static LocalDateTime[] getStAndEtAnWeek(@Nonnull Integer year,
                                               @Nonnull Integer week) {
    // 传入的那一周的周一和周日
    LocalDate startDate = LocalDate.of(year, 1, 1).plusWeeks(week - 1).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    LocalDate endDate = LocalDate.of(year, 1, 1).plusWeeks(week - 1).with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
    // 如果本年第一周的周一落在了上一年, 则将下一周作为本年的第一周
    LocalDate firstWeekMonDay = LocalDate.of(year, 1, 1).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    if (firstWeekMonDay.getYear() < year) {
        startDate = startDate.plusWeeks(1);
        endDate = endDate.plusWeeks(1);
    }
    // 如果周一落在了下一年,则传入的周数超出了当前年的范围
    if (startDate.getYear() > year) {
        throw new IllegalArgumentException("传入的周数超出了当前年的范围");
    }
    return new LocalDateTime[]{startDate.atTime(LocalTime.MIN), endDate.atTime(LocalTime.MAX)};
}
皖ICP备2024056275号-1
发表了78篇文章 · 总计148.99k字
本站已稳定运行