Java 获取一个月的第一个星期一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23971439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the first Monday of a month
提问by Jakob Abfalter
I want to get the day on which the first Monday of a specific month/year will be.
我想获得特定月份/年份的第一个星期一的日期。
What I have:
我拥有的:
I basically have two int variables, one representing the year and one representing the month.
我基本上有两个 int 变量,一个代表年份,一个代表月份。
What I want to have:
我想要的:
I want to know the first Monday in this month, preferably as an int or Integer value.
我想知道这个月的第一个星期一,最好是 int 或 Integer 值。
For example:
例如:
I have 2014 and 1 (January), the first Monday in this month was the 6th, so I want to return 6.
我有2014和1(一月),这个月的第一个星期一是6号,所以我想返回6。
Problems:
问题:
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
但我已经在设置只有年和月可用的日历时遇到了麻烦。此外,我不确定如何使用Calendar
.
I already tried this:
我已经试过了:
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));
}
采纳答案by Octavia Togami
getFirstDayOfWeek()
returns which day is used as the start for the current locale. Some people consider the first day Monday, others Sunday, etc.
getFirstDayOfWeek()
返回哪一天用作当前语言环境的开始。有些人认为第一天是星期一,其他人是星期天,等等。
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.
这看起来你必须设置它DAY_OF_WEEK = MONDAY
,DAY_OF_WEEK_IN_MONTH = 1
因为这会给你这个月的第一个星期一。要对年份执行相同的操作,首先将MONTH
值设置为JANUARY
然后重复上述操作。
Example:
例子:
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);
}
Here's a simple JUnit that tests it: http://pastebin.com/YpFUkjQG
这是一个测试它的简单 JUnit:http: //pastebin.com/YpFUkjQG
回答by Bohemian
The method getFirstDayOfWeek()
is not helpful. Quoting its javadoc:
该方法getFirstDayOfWeek()
没有帮助。引用它的javadoc:
Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France
获取一周的第一天是什么;例如,美国的星期日,法国的星期一
The following testedmethod uses modulus arithmetic to find the day of the month of the first Monday:
以下经过测试的方法使用模数算法来查找第一个星期一的月份日期:
public static long getMondaysDay(int year, int month) {
try {
Date d = new SimpleDateFormat("d-M-yyyy").parse("1-" + month + "-" + year);
long epochMillis = d.getTime() + TimeZone.getDefault().getOffset(d.getTime());
return (12 - TimeUnit.MILLISECONDS.toDays(epochMillis) % 7) % 7;
} catch (ParseException ignore) { return 0; } // Never going to happen
}
Knowing that the first day of the epochwas Thursday, this works by using modulus arithmetic to calculate the day of the epoch week, then how many days until the next Monday, then modulus again in case the first falls before Thursday. The magic number 12
is 4
(the number of days from Thursday to Monday) plus 1
because days of the month start from 1
plus 7
to ensure positive results after subtraction.
知道纪元的第一天是星期四,这通过使用模数算法来计算纪元周的日期,然后到下一个星期一的天数,然后再次模数,以防第一个在星期四之前下降。神奇的数字12
是4
(从星期四到星期一的天数)加号,1
因为一个月的天数从1
加号开始,7
以确保减法后的结果为正。
回答by Abhishek Mishra
First of all you should know the latest version of java i.e. JAVA8Get familiar with LocalDate
in JAVA8
首先你应该知道最新版本的java ie JAVA8熟悉LocalDate
在JAVA8
Then only go through below code
然后只通过下面的代码
public class Test {
public static void main(String[] args) {
LocalDate date=LocalDate.of(2014,1, 1);
for(int i=0;i<date.lengthOfMonth();i++){
if("Monday".equalsIgnoreCase(date.getDayOfWeek().toString())){
break;
}else{
date=date.plusDays(1);
}
}
System.out.println(date.getDayOfMonth());
}
}
回答by Basil Bourque
Joda-Time
乔达时间
The Joda-Timelibrary offers a class, LocalDate
, for when you need only a date without a time-of-day. The method getDayOfWeek
returns a number you can compare to the constant MONDAY
.
该乔达时库提供一个类LocalDate
,当你只需要日期没有时间的一天。该方法getDayOfWeek
返回一个可以与常量进行比较的数字MONDAY
。
LocalDate localDate = new LocalDate( year, month, 1 );
while ( localDate.getDayOfWeek() != DateTimeConstants.MONDAY ) {
localDate = localDate.plusDays( 1 );
}
int firstMonday = localDate.getDayOfMonth();
Immutable Syntax
不可变语法
For thread-safety, Joda-Time uses immutable objects. So rather than modify field values in an existing object, we create a new instance based on the original.
为了线程安全,Joda-Time 使用不可变对象。因此,我们不是修改现有对象中的字段值,而是基于原始对象创建一个新实例。
java.time
时间
As another answer by Abhishek Mishrasays, the new java.time packagebundled with Java 8also offers a LocalDate
class similar to Joda-Time.
正如Abhishek Mishra 的另一个回答所说,与Java 8捆绑在一起的新java.time 包还提供了一个类似于 Joda-Time 的类。LocalDate
回答by Max
Lamma Datelibrary is very good for this use case.
Lamma Date库非常适合这个用例。
@Test
public void test() {
assertEquals(new Date(2014, 1, 6), firstMonday(2014, 1));
assertEquals(new Date(2014, 2, 3), firstMonday(2014, 2));
assertEquals(new Date(2014, 3, 3), firstMonday(2014, 3));
assertEquals(new Date(2014, 4, 7), firstMonday(2014, 4));
assertEquals(new Date(2014, 5, 5), firstMonday(2014, 5));
assertEquals(new Date(2014, 6, 2), firstMonday(2014, 6));
}
public Date firstMonday(int year, int month) {
Date firstDayOfMonth = new Date(year, month, 1);
return firstDayOfMonth.nextOrSame(DayOfWeek.MONDAY);
}
回答by Przemek
Java.time
时间
Use java.time
library built into Java 8 and TemporalAdjuster. See Tutorial.
使用java.time
内置于 Java 8 和TemporalAdjuster 的库。请参阅教程。
import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.temporal.TemporalAdjusters.firstInMonth;
LocalDate now = LocalDate.now(); //2015-11-23
LocalDate firstMonday = now.with(firstInMonth(DayOfWeek.MONDAY)); //2015-11-02 (Monday)
If you need to add time information, you may use any available LocalDate
to LocalDateTime
conversion like
如果您需要添加时间信息,您可以使用任何可用LocalDate
的LocalDateTime
转换如
firstMonday.atStartOfDay() # 2015-11-02T00:00
回答by Sujan
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/YYYY");
calendar.set(Calendar.MONTH,Calendar.JUNE);
calendar.set(Calendar.DAY_OF_MONTH,1);
int day = (Calendar.TUESDAY-calendar.get(Calendar.DAY_OF_WEEK));
if(day<0){
calendar.add(Calendar.DATE,7+(day));
}else{
calendar.add(Calendar.DATE,day);
}
System.out.println("First date is "+sdf.format(calendar.getTime()));
回答by KayV
The simplest way is:
最简单的方法是:
LocalDate firstSundayOfNextMonth = LocalDate
.now()
.with(firstDayOfNextMonth())
.with(nextOrSame(DayOfWeek.MONDAY));
回答by M. Franklin
Here is a general function to get the nth DAY_OF_WEEK of a given month. You can use it to get the first Monday of any given month.
这是获取给定月份的第 n 个 DAY_OF_WEEK 的通用函数。您可以使用它来获取任何给定月份的第一个星期一。
import java.util.Calendar;
public class NthDayOfWeekOfMonth {
public static void main(String[] args) {
// get first Monday of July 2019
Calendar cal = getNthDayOfWeekOfMonth(2019,Calendar.JULY,1,Calendar.MONDAY);
System.out.println(cal.getTime());
// get first Monday of August 2019
cal = getNthDayOfWeekOfMonth(2019,Calendar.AUGUST,1,Calendar.MONDAY);
System.out.println(cal.getTime());
// get third Friday of September 2019
cal = getNthDayOfWeekOfMonth(2019,Calendar.SEPTEMBER,3,Calendar.FRIDAY);
System.out.println(cal.getTime());
}
public static Calendar getNthDayOfWeekOfMonth(int year, int month, int n, int dayOfWeek) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,month);
cal.set(Calendar.DAY_OF_MONTH,1);
int dayDiff = dayOfWeek-cal.get(Calendar.DAY_OF_WEEK);
if (dayDiff<0) {
dayDiff+=7;
}
dayDiff+=7*(n-1);
cal.add(Calendar.DATE, dayDiff);
return cal;
}
}
Output:
输出:
Mon Jul 01 00:00:00 EDT 2019
Mon Aug 05 00:00:00 EDT 2019
Fri Sep 20 00:00:00 EDT 2019
回答by Ganesh Giri
Get the All Monday of a month
public class AllMonday {
public static void main(String[] args){
System.out.println(weeksInCalendar(YearMonth.now()));
}
public static List<LocalDate> weeksInCalendar(YearMonth month) {
List<LocalDate> firstDaysOfWeeks = new ArrayList<>();
for (LocalDate day = firstDayOfCalendar(month);
stillInCalendar(month, day); day = day.plusWeeks(1)) {
firstDaysOfWeeks.add(day);
}
return firstDaysOfWeeks;
}
private static LocalDate firstDayOfCalendar(YearMonth month) {
DayOfWeek FIRST_DAY_OF_WEEK = DayOfWeek.of(1);
System.out.println( month.atDay(1).with(FIRST_DAY_OF_WEEK));
return month.atDay(1).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
}
private static boolean stillInCalendar(YearMonth yearMonth, LocalDate day) {
System.out.println(!day.isAfter(yearMonth.atEndOfMonth()));
return !day.isAfter(yearMonth.atEndOfMonth());
}
}
}