佐达时间:获得第一/第二/最后一个月的星期日 [英] Joda-Time: Get first/second/last sunday of month

查看:114
本文介绍了佐达时间:获得第一/第二/最后一个月的星期日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Calendar getNthOfMonth(int n, int day_of_week,int month,int year){
Calendar compareDate = Date(1,month,year);
compareDate.set(DAY_OF_WEEK,day_of_week);
compareDate.set(DAY_OF_WEEK_IN_MONTH,n);
return compareDate;
}
//用法
日历lastSundayOfNovember = getNthOfMonth(-1,SUNDAY,NOVEMBER,2012)

使用清晰优雅的方式=nofollow> Joda-Time

解决方案

  public class Time {
public static void main(String [] args){
System.out.println(getNthOfMonth(DateTimeConstants.SUNDAY,DateTimeConstants.SEP,2012 ));
}


public static LocalDate getNthOfMonth(int day_of_week,int month,int year){
LocalDate date = new LocalDate(year,month,1).dayOfMonth ()
.withMaximumValue()
.dayOfWeek()
.setCopy(day_of_week);
if(date.getMonthOfYear()!= month){
return date.dayOfWeek()。addToCopy(-7);
}
返回日期;
}
}


In plain Java, I have this code to get the last Sunday of the month.

Calendar getNthOfMonth(int n, int day_of_week, int month, int year) {
    Calendar compareDate = Date(1, month, year);
    compareDate.set(DAY_OF_WEEK, day_of_week);
    compareDate.set(DAY_OF_WEEK_IN_MONTH, n);
    return compareDate;
}
// Usage
Calendar lastSundayOfNovember = getNthOfMonth(-1, SUNDAY, NOVEMBER, 2012)

What is a clean and elegant way to achieve the same result using Joda-Time?

解决方案

public class Time {
public static void main(String[] args) {
    System.out.println(getNthOfMonth(DateTimeConstants.SUNDAY, DateTimeConstants.SEP, 2012));
}


public static LocalDate getNthOfMonth(int day_of_week, int month, int year) {
    LocalDate date = new LocalDate(year, month, 1).dayOfMonth()  
             .withMaximumValue()
             .dayOfWeek()
             .setCopy(day_of_week);
    if(date.getMonthOfYear() != month) {
        return date.dayOfWeek().addToCopy(-7);
    }
    return date;
}
}

这篇关于佐达时间:获得第一/第二/最后一个月的星期日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆