引入joda-time
<!--jodatime--> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10</version> </dependency>
1.字符串转joda-time的DateTime
parse日期
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime dateTime = DateTime.parse(date, fmt);
parse时间戳
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); DateTime dt = DateTime.parse(dateStr, format);
转换时区
DateTimeFormatter format = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss yyyy").withLocale(Locale.ENGLISH); DateTime dt = DateTime.parse(dateStr, format);
2.joda-time的DateTime转字符串
String date = dt.toString("yyyy-MM-dd"); String datetime = dt.toString("yyyy-MM-dd HH:mm:ss"); String datetime = dt.toString("yyyy-MM-dd HH:00:00"); // 整点
3.获取当前时间
DateTime now = new DateTime();
4.比较2个DateTime的时间差
Days.daysBetween(dateTime, now).getDays() > 7