joda.time的常用api
前置准备
jdk给我们提供操作时间的类,一般用Calendar;但是在比较复杂的时候,还是无法满足一般的使用,所以在常的时候,我们一般会用 joda-time 的这个工具类 来完成我们的需要;
所以我们在使用的时候 需要用maven来引入
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
获取时间
LocalDateTime localDateTime = LocalDateTime.now();
localDateTime = localDateTime.plusDays(1) // 增加天
.plusYears(1)// 增加年
.plusMonths(1)// 增加月
.plusWeeks(1)// 增加星期
.minusMillis(1)// 减分钟
.minusHours(1)// 减小时
.minusSeconds(1);// 减秒数
//获取本月指定日期 本月20号
LocalDateTime localDate = LocalDateTime.now().withDayOfMonth(20);
//获取本月最后一天
LocalDateTime lastLocalDate = LocalDateTime.now().dayOfMonth().withMaximumValue();
//获取本月第一天
LocalDateTime minLocalDate = LocalDateTime.now().dayOfMonth().withMinimumValue();
//组合使用 获取上月的倒数第二天
LocalDateTime data = LocalDateTime.now().minusMonths(1).minusDays(1).dayOfMonth().withMaximumValue();
计算时间的差异
//可用于操作 LocalDateTime
// joda-time 计算两个时间的相差时间天数
LocalDate start = new LocalDate(2018, 1, 18);
LocalDate end = new LocalDate(2018, 1, 20);
int days = Days.daysBetween(start, end).getDays();
// joda-time 计算两个时间的相差时间月数
LocalDate startMonth = new LocalDate(2018, 1, 1);
LocalDate endMonth = new LocalDate(2020, 1, 1);
int months = Months.monthsBetween(startMonth, endMonth).getMonths();
时间的转换
//data 转换为 LocalDateTime
LocalDateTime localDate = LocalDateTime.fromDateFields(new Date());
//字符串 转换为 LocalDateTime
LocalDateTime parse = localDate.parse("2018-11-11");
// LocalDateTime 转换为 date
Date date = localDate.toDate();
// LocalDateTime 转 字符串
String time = parse.toString("yyyy-MM-dd HH:mm:ss");
Java 日期比较大小
使用 truncatedCompareTo(Calendar cal1, Calendar cal2, int field) 判断时间大小,可以设置根据年、月、日、时、分、秒判断
(导包org.apache.commons.lang3.time.DateUtils;)
cal1 > cal2 返回 1
cal1 = cal2 返回 0
cal1 < cal2 返回 -1
field 取值:Calendar.YEAR、Calendar.MONTH、Calendar.DATE 等等等……
注:joda.time的常用有LocalDate, LocalTime,DateTime;但是个人觉得 方便使用的 还是LocalDateTime
本文详细介绍Joda-Time库的使用方法,包括前置准备、时间的获取与计算、时间差异计算、时间转换及日期比较。通过实例展示了如何利用Joda-Time进行复杂的日期时间操作。
1156

被折叠的 条评论
为什么被折叠?



