我正在尝试制作一个应用程序,其中包括告诉下周四的时间。每次我打开该类,应用程序都会崩溃。
@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中实现,但是我不知道是否以及如何实现,因此在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/