在Java中获取当前周的开始和结束日期 - (MONDAY TO SUNDAY) [英] Get current week start and end date in Java - (MONDAY TO SUNDAY)
问题描述
今天是2014-04-06 - SUNDAY。
Today is 2014-04-06 - SUNDAY.
使用以下代码的输出是: -
开始日期= 2014-04-07
Start Date = 2014-04-07
结束日期= 2014-04-13
End Date = 2014-04-13
我希望输出为: -
开始日期= 2014-03-31
Start Date = 2014-03-31
结束日期= 2014-04-06
End Date = 2014-04-06
// Get calendar set to current date and time
Calendar c = GregorianCalendar.getInstance();
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
System.out.println("Start Date = " + startDate);
System.out.println("End Date = " + endDate);
推荐答案
我相信只需使用:
c.setFirstDayOfWeek(Calendar.MONDAY);
将解决您的问题...:)
will resolve your issue... :)
说明 :
EXPLANATION:
在我看来,现在,您的第一天似乎设置在 Calendar.SUNDAY
上。我相信这取决于您的区域设置。
In my opinion, right now, your first day of week seems to be set on Calendar.SUNDAY
. I believe that this depends on your Locale.
因此,一个(更好的)替代将初始化您的日历
,指定您感兴趣的 Locale
...
例如: c#GregorianCalendar.getInstance(Locale.US);
Thus, a (better?) alternative would be to initialise your Calendar
specifying the Locale
you're interested in...
For example:
Calendar c = GregorianCalendar.getInstance(Locale.US);
...将给您您当前的输出,而:
... will give you your current output, while:
Calendar c = GregorianCalendar.getInstance(Locale.FRANCE);
...将给您您的预期输出;)
... will give you your expected output ;)
这篇关于在Java中获取当前周的开始和结束日期 - (MONDAY TO SUNDAY)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!