更好的Java时间处理工具Joda-Time

1、核心对象:

DateTimeFormatter 日期格式化与解析

LocalDate 本地日期(没有时间,没有时区)

LocalTime 本地时间(没有日期,没有时区)

LocalDateTime 本地日期时间(没有时区)

DateTime 日期时间(支持时区转换)

LocalDate、LocalTime、LocalDateTime、DateTime 使用方法与Java8的类似。


2、获取本周一、本周日、上周一、上周日的日期

// 本周一 零点零分零秒
LocalDateTime ldt = LocalDateTime.now(); // 2019-08-01 18:00:00 当前时间
LocalDateTime mondayOfWeek = ldt.withDayOfWeek(DateTimeConstants.MONDAY);
mondayOfWeek = mondayOfWeek.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
dtf.print(mondayOfWeek); // 2019-07-29 00:00:00

// 本周日 23点59分59秒
ldt = LocalDateTime.now(); // 2019-08-01 18:00:00 当前时间
LocalDateTime sundayOfWeek = ldt.withDayOfWeek(DateTimeConstants.SUNDAY);
sundayOfWeek = sundayOfWeek.withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);
dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
dtf.print(sundayOfWeek); // 2019-08-04 23:59:59

// 上周一 零点零分零秒
ldt = LocalDateTime.now(); // 2019-08-01 18:00:00 当前时间
ldt = ldt.minusWeeks(1);
LocalDateTime lastMondyOfWeek = ldt.withDayOfWeek(DateTimeConstants.MONDAY);
lastMondyOfWeek = lastMondyOfWeek.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
dtf.print(lastMondyOfWeek); // 2019-07-22 00:00:00

// 上周日 23点59分59秒
ldt = LocalDateTime.now(); // 2019-08-01 18:00:00 当前时间
ldt = ldt.minusWeeks(1);
LocalDateTime lastSundayOfWeek = ldt.withDayOfWeek(DateTimeConstants.SUNDAY);
lastSundayOfWeek = lastSundayOfWeek.withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);
dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
dtf.print(lastSundayOfWeek); // 2019-07-28 23:59:59

3、maven引用

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.3</version>
</dependency>
发布了25 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/lercent/article/details/98087265