LocalDateTime Java-获取下个月的星期几 [英] LocalDateTime Java - Get same day of week for next month

查看:1416
本文介绍了LocalDateTime Java-获取下个月的星期几的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期和一个月的时间,例如 31/01/2020 14:00:00 ,这是一月的最后一个星期五。如何获得2月,3月等的最后一个星期五的日期?它应该是动态的,因为可以输入任何日期,例如每个月的第二个星期二,依此类推。

I have a date and a time of a month, for example 31/01/2020 at 14:00:00, this is the last friday of January. How can I get the date for the last Friday of Feb, March, etc.? It should be dynamic because any date can come in, like the second Tuesday of any month and so on.

我正在尝试以下操作而没有运气:

I am trying with the following with no luck:

LocalDateTime startTime = LocalDateTime.of(2020, 1, 31, 14, 0, 0);

final Calendar calendar = Calendar.getInstance();
calendar.set(startTime.getYear(), startTime.getMonthValue() - 1, startTime.getDayOfMonth(), startTime.getHour(), startTime.getMinute(), startTime.getSecond());

int ordinal = calendar.get(Calendar.WEEK_OF_MONTH);
startTime = startTime.plusMonths(1).with(TemporalAdjusters.dayOfWeekInMonth(ordinal, startTime.getDayOfWeek();
System.out.println(startTime);

它正在打印 2020年6月3日(3月6日)14:00:00 这是错误的,应该是 2020/02/28

it's printing 06/03/2020 (six of march) at 14:00:00 which is wrong and should be 28/02/2020

我丢失了什么?

谢谢!

推荐答案

如前所述,一周中的哪一天有一些歧义$ b表示您指的是月中的第几天,即您指的是一周中的第 n 天,还是每月的最后 n 天。

As mentioned before, there is some ambiguity in which day of the week of the month you mean, that is, whether you mean the nth day of week or the last nth day of week of the month.

一个这样的示例是2020年2月24日,星期一。这是2020年2月的第四个也是最后一个星期一。如果您要尝试确定2020年3月的星期一,您会选择哪个星期一?第四个星期一是3月23日,但最后一个星期一是3月30日。

One such example is Monday, February 24th, 2020. It is the fourth and last Monday of February 2020. If you are going to try to determine this for March 2020, which Monday would you pick? The fourth Monday is 23 March, but the last Monday is 30 March.

因此,显然,您需要区分是向前还是向后计数。

So apparently, you'll need to distinguish between whether you count forward or backward.

例如,您可以创建一个表示一个月中某一天的类。它包含三个字段:星期几,头寸以及头寸是否倒退。例如,

You could, for instance, create a class which represents a certain day of week in a month. This holds three fields: a day-of-week, a position, and whether the position is backwards or not. E.g.


  • 每月的第二个星期一 将有

dayOfWeek = DayOfWeek.MONDAY
position = 2
backwards = false

and

每月的最后一个星期四

dayOfWeek = DayOfWeek.THURSDAY
position = 1
backwards = true


public class WeekdayInMonth {

    private final boolean backwards;

    private final DayOfWeek dayOfWeek;

    private final int position;

    private WeekdayInMonth(DayOfWeek dayOfWeek, int position, boolean backwards) {
        if (position < 1 || position > 5) {
            throw new DateTimeException("Position in month must be between 1 and 5 inclusive");
        }
        this.dayOfWeek = dayOfWeek;
        this.position = position;
        this.backwards = backwards;
    }
}

我们可以添加工厂方法来创建 WeekdayInMonth LocalDate s:

We could add factory methods to create WeekdayInMonths from LocalDates:

public static WeekdayInMonth of(LocalDate date) {
    int positionInMonth = (date.getDayOfMonth() - 1) / 7 + 1;
    return new WeekdayInMonth(date.getDayOfWeek(), positionInMonth, false);
}

private static WeekdayInMonth ofReversing(LocalDate date) {
    int lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
    int positionInMonth = (lastDayOfMonth - date.getDayOfMonth()) / 7 + 1;
    return new WeekdayInMonth(date.getDayOfWeek(), positionInMonth, true);
}

最后,我们添加了获取的方法 YearMonth 的LocalDate 调整为WeekdayInMonth。

At last, we add a method to get a LocalDate from a YearMonth adjusted to the WeekdayInMonth.

public LocalDate toLocalDate(YearMonth yearMonth) {
    // Get a temporal adjuster to adjust a LocalDate to match a day-of-the-week
    TemporalAdjuster adjuster = this.backwards ? TemporalAdjusters.lastInMonth(this.dayOfWeek) : TemporalAdjusters.firstInMonth(this.dayOfWeek);

    int weeks = this.position - 1;
    LocalDate date = yearMonth.atDay(1)
            .with(adjuster)
            .plusWeeks(this.backwards ? 0 - weeks : weeks);
    if (!Objects.equals(yearMonth, YearMonth.from(date))) {
        throw new DateTimeException(String.format("%s #%s in %s does not exist", this.dayOfWeek, this.position, yearMonth));
    }
    return date;
}

工作示例

在Ideone有一个可行的例子


如果出现初始日期,我会收到类似的错误是2020年1月1日:java.time.DateTimeException:2020-02中的星期五#5不存在。万一发生这种情况,我如何获得上一个工作日?在这种情况下,我将如何获得上一个星期五?

I am getting errors like this if the initial date is Jan 1 2020: java.time.DateTimeException: FRIDAY #5 in 2020-02 does not exist. How could I get the previous weekday in case this happens? In this case, how would I get the previous Friday?

那么,那么您需要调整LocalDate使其位于指定的年月。由于每个月至少有四个星期几,最多不超过五个星期,因此差异永远不会超过一周。我们可以删除抛出新的DateTimeException 行之后,只需使用 plusWeeks 调整返回的LocalDate。

Well, then you need to adjust your LocalDate so that it falls within the specified yearmonth. Since every month has at least four day-of-the-weeks and no more than five of them, the difference is never more than a week. We could, after removing the throw new DateTimeException line, simply adjust the returned LocalDate using plusWeeks.

我已经创建了上述示例,并添加了 toAdjustingLocalDate 方法。

I've forked the abovementioned example and added the toAdjustingLocalDate method.

这篇关于LocalDateTime Java-获取下个月的星期几的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆