Android的Google日历:一周的第一天和最后一天 - >零一个月 [英] Android Calendar: first and last day of week -> zero month

查看:447
本文介绍了Android的Google日历:一周的第一天和最后一天 - >零一个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要得到当前一周的第一个星期五当前星期。

I want to get the date of the first monday of the current week and the first friday of the current week.

我尝试了这种方式:

    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日),输出如下:

If I try this script today (Sunday, 26.1.2014), the output is the following:

20.0.2014 - 24.0.2014

20.0.2014 - 24.0.2014

修正将是2014年1月20日 - 2014年1月24日

Correct would be 20.1.2014 - 24.1.2014

是否有人知道为什么我一个月为零?

Does somebody knows why my month is zero?

推荐答案

中的JavaDoc:

From the JavaDocs:

GET 设置指示一个月场数。这是一个特定于日历的值。在格里高利历和儒略历中一年中的第一个月是一月是0;最后取决于几个月在一年的数目

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.

因此​​,第一个月(1月)有一个 0 的价值,而不是 1 (如你所期望)。

Thus the first month (January) has a MONTH value of 0, and not 1 (as you'd expect).

有一个更好的解决方案,但:使用 日期格式 或的 的SimpleDateFormat 对日期进行格式为文本。这样一来,您只需不必担心的这件事,让日期格式照顾它。例如:

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())
);

这篇关于Android的Google日历:一周的第一天和最后一天 - >零一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆