Java 时间:下个星期五怎么去?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1636038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:03:16  来源:igfitidea点击:

Time: How to get the next friday?

javadatedatetimetimejodatime

提问by michael.kebe

How can I get the next friday with the Joda-TimeAPI.

如何使用Joda-TimeAPI获得下一个星期五。

The LocalDateof today is today. It looks to me you have to decide whever you are before or after the friday of the current week. See this method:

LocalDate今天的是today。在我看来,你必须决定你在本周星期五之前还是之后。看这个方法:

private LocalDate calcNextFriday(LocalDate d) {
    LocalDate friday = d.dayOfWeek().setCopy(5);
    if (d.isBefore(friday)) {
        return d.dayOfWeek().setCopy(5);
    } else {
        return d.plusWeeks(1).dayOfWeek().setCopy(5);
    }
}

Is it possible to do it shorter or with a oneliner?

是否可以缩短或使用oneliner?

PS: Please don't advise me using JDKs date/time stuff. Joda-Time is a much better API.

PS:请不要建议我使用 JDK 日期/时间的东西。Joda-Time 是一个更好的 API。

Java 8 introduces java.timepackage (Tutorial) which is even better.

Java 8 引入了更好的 java.time包(教程)。

采纳答案by michael.kebe

java.time

时间

With the java.timeframework built into Java 8 and later (Tutorial) you can use TemporalAdjustersto get nextor previousday-of-week.

使用Java 8 及更高版本(教程)中内置的java.time框架,您可以使用获取下一个上一个星期几TemporalAdjusters

private LocalDate calcNextFriday(LocalDate d) {
  return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
}

回答by Esko

It's possible to do it in a much easier to read way:

有可能以更容易阅读的方式做到这一点:

if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
    return d.withDayOfWeek(DateTimeConstants.FRIDAY));
} else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
    // almost useless branch, could be merged with the one above
    return d;
} else {
    return d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
}

or in a bit shorter form

或以更短的形式

private LocalDate calcNextFriday(LocalDate d) {    
    if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
        d = d.withDayOfWeek(DateTimeConstants.FRIDAY));
    } else {
        d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
    }    
    return d; // note that there's a possibility original object is returned
}

or even shorter

甚至更短

private LocalDate calcNextFriday(LocalDate d) {
    if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
        d = d.plusWeeks(1);
    }
    return d.withDayOfWeek(DateTimeConstants.FRIDAY);
}

PS. I didn't test the actual code! :)

附注。我没有测试实际代码!:)

回答by fvu

Your code in 1 line

您的代码在 1 行

private LocalDate calcNextFriday3(LocalDate d) {
    return d.isBefore(d.dayOfWeek().setCopy(5))?d.dayOfWeek().setCopy(5):d.plusWeeks(1).dayOfWeek().setCopy(5);
}

Alternative approach

替代方法

private LocalDate calcNextDay(LocalDate d, int weekday) {
    return (d.getDayOfWeek() < weekday)?d.withDayOfWeek(weekday):d.plusWeeks(1).withDayOfWeek(weekday);
}


private LocalDate calcNextFriday2(LocalDate d) {
    return calcNextDay(d,DateTimeConstants.FRIDAY);
}

somewhat tested ;-)

有点测试;-)

回答by Adam Gent

I just wasted like 30 minutes trying to figure this out myself but I needed to generically roll forward.

我只是浪费了大约 30 分钟试图自己解决这个问题,但我需要一般地向前推进。

Anyway here is my solution:

无论如何,这是我的解决方案:

public static DateTime rollForwardWith(ReadableInstant now, AbstractPartial lp) {
    DateTime dt = lp.toDateTime(now);
    while (dt.isBefore(now)) {
        dt = dt.withFieldAdded(lp.getFieldTypes()[0].getRangeDurationType(), 1);
    }
    return dt;
}

Now you just need to make a Partial (which LocalDate is) for the day of the week.

现在你只需要为一周中的某一天制作一个 Partial(LocalDate 是)。

Partial().with(DateTimeFieldType.dayOfWeek(), DateTimeConstants.FRIDAY); 

Now whatever the most significant field is of the partial will be +1 if the current date is after it (now).

现在,如果当前日期在它之后(现在),那么无论该部分最重要的字段是什么,都将是 +1。

That is if you make a partial with March 2012 it will create a new datetime of March 2013 or <.

也就是说,如果您使用 2012 年 3 月进行部分制作,它将创建一个新的日期时间为 2013 年 3 月或 <。

回答by Stefan Haberl

counting bytes @fvu answer can be shortened even further to:

计算字节@fvu 答案可以进一步缩短为:

private LocalDate calcNextFriday(LocalDate d) {
  return d.plusWeeks(d.getDayOfWeek() < DateTimeConstants.FRIDAY ? 0 : 1).withDayOfWeek(DateTimeConstants.FRIDAY);
}

回答by dinesh pazani

import java.util.Calendar;

private Calendar getNextweekOfDay(int weekOfDay) {
    Calendar today = Calendar.getInstance();
    int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
    int daysUntilNextWeekOfDay = weekOfDay - dayOfWeek;
    if (daysUntilNextWeekOfDay == 0) daysUntilNextWeekOfDay = 7;
    Calendar nextWeekOfDay = (Calendar)today.clone();
    nextWeekOfDay.add(Calendar.DAY_OF_WEEK, daysUntilNextWeekOfDay);
    return nextWeekOfDay;
}

// set alarm for next Friday 9am
public void setAlarm() {
    Calendar calAlarm = getNextweekOfDay(Calendar.FRIDAY);
    calAlarm.set(Calendar.HOUR_OF_DAY, 9);//9am
    calAlarm.set(Calendar.MINUTE, 0);
    calAlarm.set(Calendar.SECOND, 0);
    scheduleAlarm(calAlarm);// this is my own method to schedule a pendingIntent
}

回答by Breton F.

A simple modulo based solution which should work with most of former java versions in case you are not allowed to upgrade your java version to java8 or onwards or to use a standard java date library as jodatime

一个简单的基于模的解决方案,它应该适用于大多数以前的 java 版本,以防您不允许将 java 版本升级到 java8 或更高版本或使用标准 java 日期库作为 jodatime

Number of days to add to your date is given by this formula :

添加到您的日期的天数由以下公式给出:

(7 + Calendar.FRIDAY - yourDateAsCalendar.get(Calendar.DAY_OF_WEEK)) % 7

(7 + Calendar.FRIDAY - yourDateAsCalendar.get(Calendar.DAY_OF_WEEK)) % 7

Note also this can be generalized for any week day by changing the static field Calendar.FRIDAY to your given weekday. Some snippet code below

另请注意,这可以通过将静态字段 Calendar.FRIDAY 更改为您给定的工作日来推广到任何工作日。下面的一些片段代码

public static void main(String[] args) {
    for (int i = 0; i < 15; i++) {

        Calendar cur = Calendar.getInstance();
        cur.add(Calendar.DAY_OF_MONTH, i);

        Calendar friday = Calendar.getInstance();
        friday.setTime(cur.getTime());
        friday.add(Calendar.DAY_OF_MONTH, (7 + Calendar.FRIDAY - cur.get(Calendar.DAY_OF_WEEK)) % 7);

        System.out.println(MessageFormat.format("Date {0} -> {1} ", cur.getTime(),  friday.getTime()));
    }
}