取周的第一天(fetch the first date of the week)

2019-07-28 22:22发布

我想用日历和日期输入为每月2月3年:: 1周数来获取一周的Java中的第一次约会

    Calendar cal = Calendar.getInstance();
    int weekOfMonth = Calendar.WEEK_OF_MONTH;
    System.out.println("weekOfMonth : " + weekOfMonth);

在此之后,我不知道该继续。

Answer 1:

有一种方法getFirstDayOfWeek()的日历类,将返回天0代表星期日,1代表星期一等on.The下面的代码片段在此基础上,并给你一周的第一天。

private static Date getFirstDateOfWeek(){
        Calendar cal = Calendar.getInstance(); 
        Date d = Calendar.getInstance().getTime();
        int currDay  =  d.getDay(); // getting the current day
        int startDay =  (currDay - cal.getFirstDayOfWeek()) + 1; // calculate the difference of number days to the current date from the first day of week
        d.setDate(d.getDate() - startDay); // setting the date accordingly.
        return d;
    }

希望这会帮助你。



Answer 2:

int year = 2012;
int month = 3 //for April(they start from 0 = January)
int week = 2;
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEEK_OF_MONTH, week);

Date date = calendar.getTime();


Answer 3:

使用java.time

首先,你可以代表年份和月份与YearMonth类。

YearMonth ym = YearMonth.of( 2017 , Month.FEBRUARY );

至于月份为期一周的的的,所以你必须定义你的条件。 你的意思是包含在第一个月的周? 或者,你的意思是第一周所有七天是当月的? 或者,你的意思是第一周的某一天-的一周?

如果你想在第一个月,问YearMonth

LocalDate firstOfMonth = ym.atDay( 1 );

为了得到含首个月的该日的一周的开始,使用TemporalAdjuster在发现TemporalAdjusters (注意复数名称)类。

LocalDate previousOrSameMondayOfFirstOfMonth = 
    firstOfMonth.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ) ;

如果你指的是含有一周的某一天的星期-第一次出现,使用其他TemporalAdjuster

LocalDate firstMondayOfMonth = 
  firstOfMonth.with( TemporalAdjusters.firstInMonth( DayOfWeek.MONDAY ) );

关于java.time

该java.time框架是建立在Java 8和更高版本。 这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar ,和SimpleDateFormat

该乔达-时间的项目,现在在维护模式 ,建议迁移到java.time类。

要了解更多信息,请参阅甲骨文教程 。 和搜索堆栈溢出了很多例子和解释。 规范是JSR 310 。

从哪里获取java.time类?

  • 的Java SE 8SE 9和后
    • 内置。
    • 具有捆绑实现标准Java API的一部分。
    • Java的9增加了一些小的功能和修复。
  • Java SE 6中SE 7
    • 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植
  • Android的
    • 所述ThreeTenABP项目适应于Android ThreeTen-反向移植 (上面提到的)特异性。
    • 请参阅如何使用ThreeTenABP ...

该ThreeTen-额外项目与其他类扩展java.time。 该项目是为将来可能增加的java.time试验场。 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多 。



文章来源: fetch the first date of the week
标签: java java-me