我正在尝试制作一个应用程序,其中包括告诉下周四的时间。每次我打开该类(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/