gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:16:13 24 4
gpt4 key购买 nike

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

我这样试过:

    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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com