简介
joda是一个java的处理时间类库,需要jdk8的支持,是java.time (jsr-310).
来自
今天在无意中学习spring的文档(9.6.2 annotation-driven formatting)的formatter的的源码的时候,发现这个时间类库,由于spring某些功能也依赖这个类库,所以我决定瞧瞧是怎么回事
功能
直接跟当前时间比较 isafternow/isbeforenow/isequalnow
返回date/calendar todate/tocalendar
时间计算,加年/月/日/时分秒 plusyears/plusmonths/plusdays
时区设置 withzone
常用函数
dt.getera();
dt.getyear();//获取当前年
dt.getweekyear();
dt.getcenturyofera();
dt.getyearofera();//世纪年
dt.getyearofcentury();
dt.getmonthofyear();//获取月份
dt.getweekofweekyear();//这周是今年的第几周
dt.getdayofyear();//这天是今年的第几天
dt.getdayofmonth();//月份的多少好
dt.getdayofweek();//一个星期的第几天
依赖
<dependency>
<groupid>joda-time</groupid>
<artifactid>joda-time</artifactid>
<version>2.9.4</version></dependency>
example code
jodatimetest.java
package com.carl.spring.hello.bean;import org.joda.time.datetime;import org.joda.time.duration;import org.joda.time.period;import org.joda.time.format.datetimeformatter;import org.joda.time.format.datetimeformatterbuilder;import org.junit.test;import java.util.date;import java.util.locale;/**
* @author carl
* @date 2016/9/2
*/public class jodatimetest { @test
public void datetimetest() { //2016/9/2
//当前时间
java.util.date judate = new date(); //如果无参,也默认是当前时间的
datetime dt = new datetime(judate);
show(dt);
} @test
public void datetimechange() {
datetime dt = new datetime(); //把年改为2000年的
datetime year2000 = dt.withyear(2000); //时间加两个小时
datetime twohourslater = dt.plushours(2);
show(dt);//2016-9-2 0:16
show(year2000);//2000-9-2 0:16
show(twohourslater);//2016-9-2 2:16
} @test
public void datetimetext() {
datetime dt = new datetime();
string monthname = dt.monthofyear().getastext(); //根据地区获取text
string frenchshortname = dt.monthofyear().getasshorttext(locale.china); boolean isleapyear = dt.year().isleap();
datetime rounded = dt.dayofmonth().roundfloorcopy();
system.out.println(monthname);
system.out.println(frenchshortname);
system.out.println(isleapyear); //月份的最后一天
system.out.println(dt.dayofmonth().getmaximumvalue());
show(rounded);
} @test
public void datetimeargs() { //实例就能够确定年月日时分秒
datetime dt = new datetime(2005, 3, 26, 12, 0, 0, 0); //这里能够进行时间的计算,plus就是加了,周期肯定是那个接口的,里面肯定也有年月日时分秒
datetime plusperiod = dt.plus(period.days(1));
datetime plusduration = dt.plus(new duration(24l*60l*60l*1000l));
show(dt);//2005-3-26 12:0
//减一天
show(dt.plusdays(-1));//2005-3-25 12:0
show(plusperiod);//2005-3-27 12:0
show(plusduration);//2005-3-27 12:0
} @test
public void datatimeformat() {
datetimeformatter fmt = new datetimeformatterbuilder()
.appenddayofmonth(1)
.appendliteral('-')
.appendmonthofyearshorttext()
.appendliteral('-')
.appendtwodigityear(1956) // pivot = 1956
.toformatter();
datetime dt = new datetime();
system.out.println(dt.tostring(fmt));//2-九月-16
} private void show(datetime datetime) {
system.out.println(datetime.getyear() + "-" + datetime.getmonthofyear() + "-" + datetime.getdayofmonth() + " " + datetime.gethourofday() + ":" + datetime.getminuteofhour());
}
}