java - 安卓日历 : first and last day of week -> zero month

标签 java android

我想获取本周第一个星期一和本周第一个星期五的日期。

我这样试过:

    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

有人知道为什么我的月份是零吗?

最佳答案

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.

因此,第一个月(一月)的 MONTH 值为 0,而不是 1(如您所料)。

不过还有一个更好的解决方案:使用 DateFormatSimpleDateFormat将日期格式化为文本。这样一来,您就不必担心,让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/

相关文章:

android - Jetpack Compose,如何测试导航?

java - Android 客户端应用程序无法正确显示服务器答案/

java - 安卓测试 : Stubbing out Retrofit with Mockito

java - 获取随机值android firebase java

java - 如何在 10 位数字的第三位和下一个第三位和下一个第四位显示带点的数字?

在意外的地方遇到 java.lang.NullPointerException

java - 使用按方法/字段访问规范的理由是什么?

java - easymock 设置对模拟对象方法参数的期望

Java:选择性比较两个集合

java - 在 Android 5+ 中将应用程序设置为使用蜂窝网络而不是 WiFi