我想获取本周第一个星期一和本周第一个星期五的日期。
我这样试过:
Calendar calendarFirstDay = Calendar.getInstance(Locale.GERMANY);
Calendar calendarLastDay = Calendar.getInstance(Locale.GERMANY);
Date now = new Date();
calendarFirstDay.setTime(now);
calendarLastDay.setTime(now);
calendarFirstDay.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendarLastDay.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
MyTextView.setText(calendarFirstDay.get(Calendar.DATE) + "." + calendarFirstDay.get(Calendar.MONTH) + "." + calendarFirstDay.get(Calendar.YEAR) + " - " + calendarLastDay.get(Calendar.DATE) + "." + calendarLastDay.get(Calendar.MONTH) + "." + calendarLastDay.get(Calendar.YEAR));
如果我今天(2014 年 1 月 26 日,星期日)尝试这个脚本,输出如下:
20.0.2014 - 24.0.2014
正确的是 20.1.2014 - 24.1.2014
有人知道为什么我的月份是零吗?
最佳答案
Field number for
get
andset
indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars isJANUARY
which is 0; the last depends on the number of months in a year.
因此,第一个月(一月)的 MONTH
值为 0
,而不是 1
(如您所料)。
不过还有一个更好的解决方案:使用 DateFormat
或 SimpleDateFormat
将日期格式化为文本。这样一来,您就不必担心,让DateFormat
来处理它。例如:
DateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
MyTextView.setText(
myFormat.format(calendarFirstDay.getTime()) + " - " +
myFormat.format(calendarLastDay.getTime())
);
关于java - 安卓日历 : first and last day of week -> zero month,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370386/