获得一个月的第一个星期一 [英] Get the first Monday of a month

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

问题描述

我希望获得特定月份/年的第一个星期一的日期。

I want to get the day on which the first Monday of a specific month/year will be.

我拥有的东西:

我基本上有两个int变量,一个代表年份,一个代表月份。

I basically have two int variables, one representing the year and one representing the month.

什么我希望:

我想知道本月的第一个星期一,最好是int或Integer值。

I want to know the first Monday in this month, preferably as an int or Integer value.

例如:

我有2014年和1月(1月),这个月的第一个星期一是第6个,所以我想要回来6。

I have 2014 and 1 (January), the first Monday in this month was the 6th, so I want to return 6.

问题:

我以为我可以用日历但我在设置只有年份和月份的日历时遇到了问题。此外,我不知道如何使用日历实际返回月/年的第一个星期一。

I thought I could do that with the Calendar but I am already having trouble setting up the calendar with only Year and Month available. Furthermore, I'm not sure how to actually return the first Monday of the month/year with Calendar.

我已经尝试过这个:

Calendar cal = Calendar.getInstance();
cal.set(this.getYear(),getMonth(), 1);
int montag = cal.getFirstDayOfWeek();
for( int j = 0; j < 7; j++ ) {
    int calc = j - montag;
    if( calc < 0 ) {
        calc += 6;
    }
    weekDays[calc].setText(getDayString(calc));
}


推荐答案

getFirstDayOfWeek()返回哪一天用作当前语言环境的开头。有些人会考虑周一的第一天,周日的其他人等等。

getFirstDayOfWeek() returns which day is used as the start for the current locale. Some people consider the first day Monday, others Sunday, etc.

这看起来你只需将其设置为 DAY_OF_WEEK = MONDAY DAY_OF_WEEK_IN_MONTH = 1 因为它会给你这个月的第一个星期一。为了在今年做同样的事情,首先将 MONTH 值设置为 JANUARY 然后重复上述步骤。

This looks like you'll have to just set it for DAY_OF_WEEK = MONDAY and DAY_OF_WEEK_IN_MONTH = 1 as that'll give you the first Monday of the month. To do the same for the year, first set the MONTH value to JANUARY then repeat the above.

示例:

private static Calendar cacheCalendar;

public static int getFirstMonday(int year, int month) {
    cacheCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    cacheCalendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
    cacheCalendar.set(Calendar.MONTH, month);
    cacheCalendar.set(Calendar.YEAR, year);
    return cacheCalendar.get(Calendar.DATE);
}

public static int getFirstMonday(int year) {
    return getFirstMonday(year, Calendar.JANUARY);
}

这是一个测试它的简单JUnit:http://pastebin.com/YpFUkjQG

Here's a simple JUnit that tests it: http://pastebin.com/YpFUkjQG

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

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