我想用日历和日期输入为每月2月3年:: 1周数来获取一周的Java中的第一次约会
Calendar cal = Calendar.getInstance();
int weekOfMonth = Calendar.WEEK_OF_MONTH;
System.out.println("weekOfMonth : " + weekOfMonth);
在此之后,我不知道该继续。
我想用日历和日期输入为每月2月3年:: 1周数来获取一周的Java中的第一次约会
Calendar cal = Calendar.getInstance();
int weekOfMonth = Calendar.WEEK_OF_MONTH;
System.out.println("weekOfMonth : " + weekOfMonth);
在此之后,我不知道该继续。
有一种方法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;
}
希望这会帮助你。
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();
首先,你可以代表年份和月份与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 8和更高版本。 这些类取代麻烦的老传统日期时间类,如java.util.Date
, Calendar
,和SimpleDateFormat
。
该乔达-时间的项目,现在在维护模式 ,建议迁移到java.time类。
要了解更多信息,请参阅甲骨文教程 。 和搜索堆栈溢出了很多例子和解释。 规范是JSR 310 。
从哪里获取java.time类?
该ThreeTen-额外项目与其他类扩展java.time。 该项目是为将来可能增加的java.time试验场。 您可以在这里找到一些有用的类,比如Interval
, YearWeek
, YearQuarter
,和更多 。