简体   繁体   中英

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:

20.0.2014 - 24.0.2014

Correct would be 20.1.2014 - 24.1.2014

Does somebody knows why my month is zero?

From the JavaDocs :

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 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).

There's a much better solution though: use a DateFormat or SimpleDateFormat to format dates as text. That way, you simply don't have to worry about this and let the DateFormat take care of it. 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)

if you use this method, January will be 0 and Decmember will be 11, so you should just add 1 to your month.

EDIT: You are using the get method but it's probably 0-based, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM