[英]Android Calendar: first and last day of week -> zero month
I want to get the date of the first monday of the current week and the first friday of the current week. 我想获取当前一周的第一个星期一的日期和当前一周的第一个星期五的日期。
I tried it this way: 我这样尝试过:
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));
If I try this script today (Sunday, 26.1.2014), the output is the following: 如果我今天(2014年1月26日,星期日)尝试此脚本,则输出如下:
20.0.2014 - 24.0.2014
20.0.2014-24.0.2014
Correct would be 20.1.2014 - 24.1.2014 正确的是20.1.2014-24.1.2014
Does somebody knows why my month is zero? 有人知道为什么我的月份为零吗?
From the JavaDocs : 从JavaDocs :
Field number for
get
andset
indicating the month.get
和set
字段号指示月份。 This is a calendar-specific value.这是日历特定的值。 The first month of the year in the Gregorian and Julian calendars is
JANUARY
which is 0;今年的阳历和罗马儒略历的第一个月是
JANUARY
是0; the last depends on the number of months in a year.最后一个取决于一年中的月份数。
Thus the first month (January) has a MONTH
value of 0
, and not 1
(as you'd expect). 因此,第一个月(一月)的
MONTH
值为0
,而不是1
(如您所期望的)。
There's a much better solution though: use a DateFormat
or SimpleDateFormat
to format dates as text. 不过,还有一个更好的解决方案:使用
DateFormat
或SimpleDateFormat
将日期设置为文本格式。 That way, you simply don't have to worry about this and let the DateFormat
take care of it. 这样,您就不必担心此问题,而让
DateFormat
来处理它。 For example: 例如:
DateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
MyTextView.setText(
myFormat.format(calendarFirstDay.getTime()) + " - " +
myFormat.format(calendarLastDay.getTime())
);
As stated in 如中所述
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#set(int,%20int,%20int) http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#set(int,%20int,%20int)
if you use this method, January will be 0 and Decmember will be 11, so you should just add 1 to your month. 如果使用此方法,则一月将为0,十月号将为11,因此您应在月份中加1。
EDIT: You are using the get
method but it's probably 0-based, too. 编辑:您正在使用
get
方法,但它也可能基于0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.