如何计算“周五之前”使用 Java 还是 Groovy?

发布于 2024-10-18 03:36:24 字数 184 浏览 1 评论 0原文

我需要能够用 Java 或 Groovy 计算今天的“星期五之前”。

例如,如果今天是 2 月 21 日星期一,则“之前的星期五”将为 2 月 18 日星期五。

如果今天是 2 月 1 日星期二,则“之前的星期五”将为 1 月 28 日星期五。

最好的方法是什么要这样做吗?我可以最有效地利用哪些现有课程?

I need to be able to calculate the "Friday before" today in Java or Groovy.

For example, if today is Monday, February 21, the "Friday before" would be Friday, February 18.

And if today was Tuesday, February 1, the "Friday before" would be Friday, January 28.

What would be the best way to do this? What existing classes can I most effectively leverage?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏の忆 2024-10-25 03:36:24

您可以使用循环:

Calendar c = Calendar.getInstance();
while(c.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY)
{
    c.add(Calendar.DAY_OF_WEEK, -1)
}

或者

Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_WEEK, -((c.get(Calendar.DAY_OF_WEEK) + 1) % 7));

You can use a loop:

Calendar c = Calendar.getInstance();
while(c.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY)
{
    c.add(Calendar.DAY_OF_WEEK, -1)
}

Or

Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_WEEK, -((c.get(Calendar.DAY_OF_WEEK) + 1) % 7));
波浪屿的海角声 2024-10-25 03:36:24

我会创建一个方法来给出自给定日期以来已经过去的天数。

// Uses now by default
public static int daysSince(int day) {
    return daysSince(day, Calendar.getInstance());
}

// Gives you the number of days since the given day of the week from the given day.
public static int daysSince(int day, Calendar now) {
    int today = now.get(Calendar.DAY_OF_WEEK);
    int difference = today - day;
    if(difference <= 0) difference += 7;
    return difference;
}

// Simple use example
public static void callingMethod() {
    int daysPassed = daysSince(Calendar.FRIDAY);
    Calendar lastFriday = Calendar.getInstance().add(Calendar.DAY_OF_WEEK, -daysPassed);
}

I would make a method that gave me the number of days that have passed since the given day.

// Uses now by default
public static int daysSince(int day) {
    return daysSince(day, Calendar.getInstance());
}

// Gives you the number of days since the given day of the week from the given day.
public static int daysSince(int day, Calendar now) {
    int today = now.get(Calendar.DAY_OF_WEEK);
    int difference = today - day;
    if(difference <= 0) difference += 7;
    return difference;
}

// Simple use example
public static void callingMethod() {
    int daysPassed = daysSince(Calendar.FRIDAY);
    Calendar lastFriday = Calendar.getInstance().add(Calendar.DAY_OF_WEEK, -daysPassed);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文