像第一个星期天,第二个星期二这样的日子

时间:2019-06-04 06:22:43

标签: android datetime calendar dayofweek

我想获得本月的一天(例如第1个星期日,第2个星期二)作为日历。 如何在Android中使用Calendar类实现此目的?谢谢。

1 个答案:

答案 0 :(得分:1)

java.time和ThreeTenABP

编辑:简洁的解决方案使用DateTimeFormatter

    Locale language = Locale.ENGLISH;

    Map<Long, String> ordinalNumber = new HashMap<>(8);
    ordinalNumber.put(1L, "1st");
    ordinalNumber.put(2L, "2nd");
    ordinalNumber.put(3L, "3rd");
    ordinalNumber.put(4L, "4th");
    ordinalNumber.put(5L, "5th");
    DateTimeFormatter dayFormatter = new DateTimeFormatterBuilder()
            .appendText(ChronoField.ALIGNED_WEEK_OF_MONTH, ordinalNumber)
            .appendPattern(" EEEE 'of the month'")
            .toFormatter(language);

    LocalDate date = LocalDate.now(ZoneId.of("Pacific/Auckland"));

    String dayString = date.format(dayFormatter);

    System.out.println("" + date + " is the " + dayString);

我刚才运行此代码段时,输出:

  

2019-06-05是该月的第一个星期三

很显然,您可以输入除今天在新西兰以外的其他任何日期。

对齐月份的概念将月份的第一周定义为1到7天,第二周是8到14天,依此类推。因此,根据该方案,当星期三在第1周时,我们也知道它必须是该月的第一个星期三。其他数字也一样。

我没有使用您提到的Calendar类,因为它的设计很差并且已经过时了。相反,我使用的是现代Java日期和时间API java.time。

原始代码(虽然短一些,但需要更多的手工工作):

    String[] ordinalNumber = { "0th", "1st", "2nd", "3rd", "4th", "5th" };

    LocalDate date = LocalDate.now(ZoneId.of("Pacific/Auckland"));

    DayOfWeek day = date.getDayOfWeek();
    int numberDowOfMonth = date.get(ChronoField.ALIGNED_WEEK_OF_MONTH);

    String dayString = String.format(language, "%s %s of the month",
            ordinalNumber[numberDowOfMonth],
            day.getDisplayName(TextStyle.FULL_STANDALONE, language));

    System.out.println("" + date + " is the " + dayString);

输出与上面相同。

我的ordinalNumber数组中有一个未使用的第0个元素。我只把它放在这里是因为数组在Java中是从0开始的,我希望其他字符串与数字对齐。

问题:我可以在Android上使用java.time吗?

是的,java.time在较新和较旧的Android设备上均可正常运行。它只需要至少 Java 6

  • 在Java 8和更高版本以及更新的Android设备(API级别26以上)中,内置了现代API。
  • 在Java 6和7中,获得了ThreeTen反向端口,这是现代类的反向端口(JSR 310的ThreeTen;请参见底部的链接)。
  • 在(较旧的)Android上,使用Android版本的ThreeTen Backport。叫做ThreeTenABP。并确保您使用子包从org.threeten.bp导入日期和时间类。

链接

相关问题