天天看點

Joda-Time幾個用法小記

Joda-Time幾個用法小記

1, 擷取每天的零點

DateTime dt=new DateTime().withMillisOfDay(0);
System.out.println(dt.toString("yyyy-MM-dd HH:mm:ss"));//結果2016-09-09 00:00:00           

複制

2, 在每天的6:30處理一些東西

DateTime dt=new DateTime().withHourOfDay(6).withMinuteOfHour(30).withSecondOfMinute(0);
System.out.println(dt.toString("yyyy-MM-dd HH:mm:ss"));//結果2016-09-09 06:30:00           

複制

3, 在每月的7号的6:30處理一些東西

DateTime dt=new DateTime().withDayOfMonth(7).withHourOfDay(6).withMinuteOfHour(30).withSecondOfMinute(0);
System.out.println(dt.toString("yyyy-MM-dd HH:mm:ss"));//結果2016-09-07 06:30:00           

複制

4, 在每年的8月的7号的6:30處理一些東西

DateTime dt=new DateTime().withMonthOfYear(8).withDayOfMonth(7).withHourOfDay(6).withMinuteOfHour(30).withSecondOfMinute(0);
System.out.println(dt.toString("yyyy-MM-dd HH:mm:ss"));//結果2016-08-07 06:30:00           

複制

5, 擷取每個月的第一天和最後一天

DateTime dateTime=new DateTime();
System.out.println(dateTime.dayOfMonth().withMinimumValue().dayOfMonth().get());
System.out.println(dateTime.dayOfMonth().withMaximumValue().dayOfMonth().get());//結果130           

複制

6, 擷取每天的零點的下一天零點

DateTime dt=new DateTime().withMillisOfDay(0).plusDays(1);
System.out.println(dt.toString("yyyy-MM-dd HH:mm:ss"));           

複制

7, 擷取日期差

DateTime start=new DateTime(2015,5,4,12,20);
        DateTime start=new DateTime(2015,5,4,12,20);
        DateTime end=new DateTime(2015,5,6,3,10);
        Period period=new Period(start,end);
        System.out.println("month:"+period.getMonths());
        System.out.println("days:"+period.getDays());
        System.out.println("hours:"+period.getHours());
        System.out.println("minutes:"+period.getMinutes());
        System.out.println("second:"+period.getSeconds());//結果month:0days:1hours:14minutes:50second:0           

複制

8, 單獨擷取天,小時,分鐘,秒

DateTime start=new DateTime(2015,5,4,12,20);
        DateTime end  =new DateTime(2015,5,5,12,00);
        System.out.println(Days.daysBetween(start,end).getDays());
        System.out.println(Hours.hoursBetween(start,end).getHours());
        System.out.println(Minutes.minutesBetween(start,end).getMinutes());
        System.out.println(Seconds.secondsBetween(start,end));           

複制

9, 時間判斷是否在某個範圍以及擷取時間差的毫秒

DateTime start=new DateTime(2015,5,4,12,20);
        DateTime end  =new DateTime(2015,5,5,12,00);
        Interval interval=new Interval(start,end);
        System.out.println(interval.contains(new DateTime(2015,5,5,11,00)));

        Duration duration=new Duration(start,end);
        System.out.println(duration.getStandardHours());           

複制

官網連接配接

http://www.joda.org/joda-time/userguide.html