有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

按多个日期时间单位进行java搜索

在表单中,我有4个字段,用户可以在其中选择列表中的日期,以搜索在该日期发生的事件:

  • 一天
  • 时辰

到目前为止,它仅在未选择任何字段(因此结果是曾经发生的所有事件)或仅在选择所有字段(因此结果是当年该月该日该小时内发生的所有事件)时起作用

我的问题是,如果只选择了一个月或一年和一个小时(所有4^4组合都可能),我不知道如何搜索。我怎样才能做到这一点


共 (1) 个答案

  1. # 1 楼答案

    你的问题很模糊,因为它不符合你的目标。我假设您正在收集输入,以便针对某个日期范围进行某种查询

    因此,我认为单独使用一年,或者一年+一个月,或者一年+一个月+一个月+一天,或者一年+一个月+一个月+一天+一个小时是有意义的,但没有其他组合

    日期时间值

    使用java。用于确定搜索日期或日期时间的时间类

    仅适用于年份,请使用^{}

    if( yearOnly ) {
        Year year = Year.of( Integer.intValue( yearFieldValue ) );
        LocalDate yearStartDate = year.atDay( 1 );
        LocalDate yearStopDate = year.atDay( year.length() ); // Year is normally 365 or 366 days long ([Leap Year][2]).
    }
    

    或者,如果你明智地使用半开放的方法来定义时间跨度,其中开始是包含的,而结束是独占的,这意味着一年从一年的第一年开始,一直到下一年的第一年,但不包括下一年的第一年

    if( yearOnly ) {
        Year year = Year.of( Integer.intValue( yearFieldValue ) );
        LocalDate targetYearStartDate = year.atDay( 1 );
        LocalDate followingYearStartDate = targetYearStartDate.plusYears( 1 );
    }
    

    如果你需要准确的时刻,那就从每天的第一刻开始。指定一个时区,因为日期开始的时间在全球各地因区域而异。应用ZoneId获取^{}对象

    ZoneId z = ZoneId.of( "America/Montreal" );
    ZonedDateTime zdtStart = targetYearStartDate.atStartOfDay( z );
    ZonedDateTime zdtStop = followingYearStartDate.atStartOfDay( z );
    

    如果它们提供年份和月份,但没有日期和时间,请使用^{}

    YearMonth ymStart = YearMonth.of( Integer.intValue( yearFieldValue ) , Integer.intValue( monthFieldValue ) );
    LocalDate ldStart = ymStart.atDay( 1 );
    LocalDate ldStop = ym.plusMonths( 1 ).atDay( 1 );  
    

    如果你有一年、一个月、一个月的某一天,直接去a LocalDate

    LocalDate ld = LocalDate.of(
        Integer.intValue( yearFieldValue ) , 
        Integer.intValue( monthFieldValue ) , 
        Integer.intValue( dayOfMonthFieldValue )
    )
    

    如果你还有一个小时,那么构造一个^{}。与LocalDateZoneId组合以获得ZonedDateTime对象

    LocalTime lt = LocalTime.of( Integer.intValue( hourFieldValue ) , 0 );
    ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
    

    用户界面

    在用户界面方面,最初只能启用年份字段。输入有效值后,启用下一个字段,依此类推

    如果你不能做到这一点,那么一种方法就是不处理错误条目。如果他们输入year和dayOfMonth,但没有输入month,那么只需搜索整年即可

    如果你想解决错误的数据输入,那么你需要用你的代码进行检查,寻找每一个好的和坏的组合