java - 在android studio中查找下周四的日期

标签 java android-studio

我正在尝试制作一个应用程序,其中包括告诉下周四的时间。每次我打开该类(class)时,应用程序都会崩溃。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_authorised);
    button.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            nextThursday();
        }
    });

}

void nextThursday(){
    String nextThursday = getNext(DayOfWeek.THURSDAY).format(DateTimeFormatter.ofPattern("MMM, dd yyyy", Locale.ENGLISH));
    nextThurs.setText(nextThursday);
}

public static LocalDate getNext(DayOfWeek dayOfWeek) {
    // get the reference day for the word "next" (that is the current day)
    LocalDate today = LocalDate.now();
    // start with tomorrow
    LocalDate next = today.plusDays(1);

    // as long as the desired day of week is not reached
    while (next.getDayOfWeek() != dayOfWeek) {
        // add one day and try again
        next = next.plusDays(1);
    }

    // then return the result
    return next;
}

}

有人可以帮忙吗?

最佳答案

此答案使用 java.time,这是自从 Joda Time 项目停止进一步开发以来要使用的日期时间 API。

它基本上使用了一种在 Joda Time 中也可以实现的算法,但我不知 Prop 体是否以及如何实现,所以我向您展示了一种在 java.time 中实现的方法。

定义一个返回一周中下一个给定日期的日期的方法:

public static LocalDate getNext(DayOfWeek dayOfWeek) {
    // get the reference day for the word "next" (that is the current day)
    LocalDate today = LocalDate.now();
    // start with tomorrow
    LocalDate next = today.plusDays(1);

    // as long as the desired day of week is not reached
    while (next.getDayOfWeek() != dayOfWeek) {
        // add one day and try again
        next = next.plusDays(1);
    }

    // then return the result
    return next;
}

并在 main() 中使用它只是为了打印出来:

public static void main(String[] args) {
    System.out.println("Next Thursday is " + 
            getNext(DayOfWeek.THURSDAY)
                .format(DateTimeFormatter.ofPattern("MMM, dd yyyy", Locale.ENGLISH)));
}

2020 年 5 月 15 日星期五执行时会产生输出:

Next Thursday is May, 21 2020

当然,格式只是一个示例,可以根据您的需要轻松调整。

关于java - 在android studio中查找下周四的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61817615/

相关文章:

android - 无法在 Android Studio 中解析符号 setAdapter 和 AttachToListView

android - 如何让按钮适合屏幕?

android-studio - 在 Android Studio 中查找并用间隙/通配符替换单词

java - EasyMock : mocking the new operation possible?

android - 牛轧糖/奥利奥的 JobScheduler

ios - 使用 Swift 创建 Flutter 项目

java - 在 Hibernate @Formula 中使用 DATE_ADD

java - 创建 Vector<Vector<String>> 以将 .txt 文件导入 JTable

java - 如何在 Spring 将其反序列化为 POJO 之前访问原始请求负载?

java - 如何创建(然后获取元素)列表的数组/列表?