Joda Time的介绍可以参考这篇文章:
http://www.ibm.com/developerworks/cn/java/j-jodatime.html
工作中也常常用到Joda Time,为了避免每次使用都查API,记录一下常用的用法:
/**
* DateTime变化(增减)
*/
@Test
public void testChange() {
DateTime dateTime = new DateTime(2014, 1, 2, 10, 11, 12);
//得到1年2个月3天后的日期
assertEquals(new DateTime(2015, 3, 5, 10, 11, 12), dateTime.plusYears(1).plusMonths(2).plusDays(3));
}
/**
* 指定值(更改DateTime的特定部分为特定值)
*/
@Test
public void testSpecific() {
DateTime dateTime = new DateTime(2014, 12, 2, 8, 12, 45, 666);
//把小时指定为13点
assertEquals(new DateTime(2014, 12, 2, 13, 12, 45, 666), dateTime.withHourOfDay(13));
}
/**
* 字符串和DateTime互转
*/
@Test
public void testToDateToString() {
String str = "2014-12-02 08:12:45";
DateTime dateTime = new DateTime(2014, 12, 2, 8, 12, 45);
//字符串转化为DateTime
DateTime parsedDateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime(str);
assertEquals(dateTime, parsedDateTime);
//DateTime转化为字符串,有两种方法
String str01 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").print(dateTime);
assertEquals(str, str01);
String str02 = dateTime.toString("yyyy-MM-dd HH:mm:ss");
assertEquals(str, str02);
}
/**
* DateTime截断
*/
@Test
public void testTruncateTo() {
DateTime dateTime = new DateTime(2014, 12, 2, 8, 12, 45, 666);
//精确到天
DateTime tillDay = dateTime.dayOfMonth().roundFloorCopy();
assertEquals(new DateTime(2014, 12, 2, 0, 0, 0), tillDay);
//精确到秒
DateTime tillSecond = dateTime.secondOfMinute().roundFloorCopy();
assertEquals(new DateTime(2014, 12, 2, 8, 12, 45), tillSecond);
}
/**
* 得到某一天的23:59:59
*/
@Test
public void testWith() {
DateTime dateTime = new DateTime(2014, 12, 2, 8, 12, 45);
//两种方法
//指定时分秒为23:59:59
assertEquals(new DateTime(2014, 12, 2, 23, 59, 59), dateTime.withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59));
//取一天中的最后一秒(秒的最大值)
assertEquals(new DateTime(2014, 12, 2, 23, 59, 59), dateTime.secondOfDay().withMaximumValue());
//得到当天的00:00:00
assertEquals(new DateTime(2014, 12, 2, 0, 0, 0), dateTime.secondOfDay().withMinimumValue());
}