检查月份,日期或年份是否在两个日期范围内 [英] Check if month or day or year is in range of two dates

查看:119
本文介绍了检查月份,日期或年份是否在两个日期范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串过滤器,只能接受3种日期格式-YYYYYYYY-MMYYYY-MM-DD.

I have a filter that is a String and can only accept 3 date-formats - YYYY, YYYY-MM, YYYY-MM-DD.

我想检查请求的字符串是否在两个日期范围内.

I want to check if the requested String is in the range of two dates.

比方说,我在记录中有两个日期(即时)-2010-05-01T00:00:00Z& 2020-03-01TT23:59:59.999999999Z

Let's say, I have two dates (Instants) in a record - 2010-05-01T00:00:00Z & 2020-03-01TT23:59:59.999999999Z

然后:

请求的日期|范围结果

2018年|在范围内

2018 | in range

2010年|范围内

2009年|不在范围内

2018-03 |在范围内

2018-03 | in range

2010-02 |不在范围内

2010-05 |范围内(感谢@Ole V.V.的更正)

2010-05 | in range (Thanks for the correction @Ole V.V.)

2012-01-05 |在范围内

2012-01-05 | in range

2020-03-01 |在范围内

2020-03-01 | in range

2020-04-01 |不在范围内

我正在使用Java时间检查日期是在给定日期之前还是之后,但是就我而言,我有一个字符串,该字符串可以是3种日期格式中的任何一种.

I am using Java time to check if a date is before or after the given dates, but in my case, I have a string that could be in any of the 3 date-formates.

我能想到的一种解决方案是,如果请求是YYYY,则仅检查它是否在两个日期的年份之间.如果请求是YYYY-MM,则检查它是否在两个日期的年和月之间.等等.但是我不确定如何使它工作.

One solution I can think of is if the request is YYYY, then only check if it is between years of the two dates. If the request is YYYY-MM, then check if it is between Year and month of the two dates. And so on. But I am not sure how to make it work.

有人可以帮助解决这个问题吗?

Can someone please help to solve this problem?

推荐答案

您可以创建自己的方法来检查您的日期是否有效,在您的问题中,您有三种不同的情况,即日期只有年份,或者只有年份和月份的日期(或完整日期),在这种情况下,当您要解析唯一的年份时,您会遇到一个小问题,我可以为您提供此解决方案:

You can create your own method to check if your date is valid of not, in your problem, you have three different cases, date which have only year, or date which have only year and month, or a full date, in this cases, you have a small problem when you want to parse the only the year, I can gives you this solution :

public static boolean isValid(String date, Instant start, Instant end) {
    LocalDate sld = start.atOffset(ZoneOffset.UTC).toLocalDate();
    LocalDate eld = end.atOffset(ZoneOffset.UTC).toLocalDate();
    try {
        LocalDate ld = LocalDate.parse(date);
        return ld.isAfter(sld) && ld.isBefore(eld);
    } catch (DateTimeParseException e) {}

    try {
        YearMonth ym = YearMonth.parse(date);
        return ym.isAfter(YearMonth.from(sld)) && ym.isBefore(YearMonth.from(eld));
    } catch (DateTimeParseException e) {}

    try {
        Year y = Year.parse(date);
        return y.isAfter(Year.from(sld)) && y.isBefore(Year.from(eld));
    } catch (DateTimeParseException e) {}
    return false;
}

这是一个 演示示例

Here is an Idemo demo

这篇关于检查月份,日期或年份是否在两个日期范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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