获得一个月的第一个星期一

时间:2014-05-31 14:56:36

标签: java

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

我有什么:

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

我想拥有的内容:

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

例如:

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

问题:

我认为我可以使用Calendar执行此操作,但我已经无法设置仅提供年份和月份的日历。此外,我不确定如何使用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));
}

9 个答案:

答案 0 :(得分:11)

getFirstDayOfWeek()返回哪一天用作当前区域设置的开头。有些人认为周一的第一天,周日的其他人等等。

看起来您只需要为DAY_OF_WEEK = MONDAYDAY_OF_WEEK_IN_MONTH = 1设置它,因为它会为您提供当月的第一个星期一。要对年份执行相同操作,请先将MONTH值设置为JANUARY,然后重复上述步骤。

示例:

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

答案 1 :(得分:4)

首先,您应该知道最新版本的Java,即 JAVA8 熟悉 JAVA8

中的LocalDate

然后只通过以下代码

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());

    }

}

答案 2 :(得分:2)

方法getFirstDayOfWeek()无效。引用它的javadoc:

  

获取一周的第一天;例如,美国的星期日,法国的星期一

以下测试的方法使用模数运算来查找第一个星期一的月中日期:

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
}

知道epoch的第一天是星期四,这可以通过使用模运算来计算纪元周的日期,然后到下一个星期一的天数,然后在第一次下降时再次计算模数星期四之前。幻数124(周四至周一的天数)加1,因为该月的天数从17开始,以确保减法后的阳性结果。

答案 3 :(得分:2)

约达时间

Joda-Time库提供了一个类LocalDate,用于何时只需要一个没有时间的日期。方法getDayOfWeek会返回一个可以与常量MONDAY进行比较的数字。

LocalDate localDate = new LocalDate( year, month, 1 );
while ( localDate.getDayOfWeek() != DateTimeConstants.MONDAY ) {
    localDate = localDate.plusDays( 1 );
}
int firstMonday = localDate.getDayOfMonth();

不可变语法

对于线程安全,Joda-Time使用immutable objects。因此,我们不是修改现有对象中的字段值,而是根据原始对象创建新实例。

java.time

正如another answer by Abhishek Mishra所述,与java.time package捆绑在一起的新Java 8也提供类似于Joda-Time的LocalDate类。

答案 4 :(得分:1)

最简单的方法是:

LocalDate firstSundayOfNextMonth = LocalDate
              .now()
              .with(firstDayOfNextMonth())
              .with(nextOrSame(DayOfWeek.MONDAY));

答案 5 :(得分:1)

这是获取给定月份的第n个DAY_OF_WEEK的常规功能。您可以使用它来获取任何给定月份的第一个星期一。

private void parserTest() {
        //https://stackoverflow.com/a/54694322
        ExpressionParser parser = new SpelExpressionParser();
        String inputString="#{replace(ABCD,\"AB\", \"PQ\")}";
        Expression exp = parser.parseExpression(inputString, new TemplateParserContext());
        String outputString = (String) exp.getValue(new StandardEvaluationContext(this));

    }

// replace function
    public String replace(String srcString, String regex, String replacement) {
            return srcString.replaceFirst(regex, replacement);
        }

输出:

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;
}

}

答案 6 :(得分:0)

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);
}

答案 7 :(得分:0)

clear;
clc;

%% Video file information
obj = VideoReader('T9_720p_60p_60mm_f5.MOV');

%% Sampling rate 
fps = get(obj, 'FrameRate');
dt = 1/fps;

%% Image Information
file_info = get(obj);
image_width = file_info.Width;
image_height = file_info.Height;

%%Desired image size
x_range = 1:image_height;
y_range = 1:image_width;
szx = length(x_range);
szy = length(y_range);

%%Image processing - Point selection
for n = 33:115
    frame = read(obj,n);
    imshow(frame);
    hpoint = impoint(gca, []);
    Position = getPosition(hpoint);
end

答案 8 :(得分:0)

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());
  }

}