Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

java - Get the first Monday of a month

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.

What I want to have:

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

For example:

I have 2014 and 1 (January), the first Monday in this month was the 6th, so I want to return 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.

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));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Java.time

Use java.time library built into Java 8 and TemporalAdjuster. See Tutorial.

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

firstMonday.atStartOfDay() # 2015-11-02T00:00

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...