如何从指定日期获取上周五的日期?

2022-01-11 00:00:00 date calendar java

我怎样才能找到上一个(前一个)星期五"的日期或从指定日期开始的任何其他日期?

How can I find out the date of last (previous) "Friday" or any other day from a specified date?

public getDateOnDay(Date date, String dayName) {
    // ?
}

推荐答案

我不会给出答案(先自己试试吧!),但是,也许这些提示可以帮助你.

I won't give an answer (try it yourself first!), but, maybe these tips can help you out.

  1. 您首先需要确定您所在的星期几.您可能想看看 Java 的 日历类来了解如何做到这一点.
  2. 一旦您获得了您所在的日期,请考虑模数运算符以及如何使用它向后移动以从您当前所在的那一天开始获取您正在寻找的前一天.(请记住,一周有 7 天,一周中的每一天在这 7 天中占据一个空档".)
  3. 一旦确定了两者之间的天数,您就会想减去.当然,Java框架中也有可以为你加减天数的类……
  1. You first need to figure out the current day of the week you are on. You may want to take a look at Java's Calendar class to get an idea of how to do that.
  2. Once you get the date you are on, think about the modulus operator and how you can use that to move backwards to pick up the previous day that you are looking for from the day you are currently at. (Remember, a week is 7 days and each day of the week takes up a "slot" in those 7 days.)
  3. Once you have the number of days in between, you'll want to subtract. Of course, there are classes that can add and subtract days for you in the Java framework...

我希望这会有所帮助.再次,我鼓励你总是先自己尝试这个问题.从长远来看,您可以通过这种方式学到更多东西,并成为更好的开发人员.

I hope that helps. Again, I encourage you to always try the problem for yourself, first. You learn far much more that way and be a better developer in the long run for it.

相关文章