下周四在Android Studio中使用joda的查找日期

问题描述 投票:0回答:1

我正在尝试制作一个包含告诉下周四时间的应用程序。我正在使用joda来执行此操作,但是它使我的应用程序崩溃了。

public class authorised extends AppCompatActivity {
TextView nextThurs = findViewById(R.id.date);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_authorised);


    LocalDate today = LocalDate.now();
    int old;
    old = today.getDayOfWeek();
    int thursday = 4;

    if (thursday <= old) thursday = thursday + 7;

    LocalDate next = today.plusDays(thursday - old);

    String nextThursday = String.valueOf(next);
    nextThurs.setText(nextThursday);

}

}

有人能帮忙吗?

java android-studio jodatime android-jodatime
1个回答
0
投票

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

[它基本上使用的算法也可以在Joda Time中实现,但是我不知道是否以及如何,所以我在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

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

© www.soinside.com 2019 - 2024. All rights reserved.