001/*- 002 * #%L 003 * HAPI FHIR - Core Library 004 * %% 005 * Copyright (C) 2014 - 2023 Smile CDR, Inc. 006 * %% 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 * #L% 019 */ 020package ca.uhn.fhir.util; 021 022import ca.uhn.fhir.rest.param.DateRangeParam; 023 024import javax.annotation.Nonnull; 025import javax.annotation.Nullable; 026import java.util.Date; 027 028public class DateRangeUtil { 029 030 /** 031 * Narrow the DateRange to be within theStartInclusive, and theEndExclusive, if provided. 032 * @param theDateRangeParam the initial range, null for unconstrained 033 * @param theStartInclusive a lower bound to apply, or null for unchanged. 034 * @param theEndExclusive an upper bound to apply, or null for unchanged. 035 * @return a DateRange within the original range, and between theStartInclusive and theEnd 036 */ 037 @Nonnull 038 public static DateRangeParam narrowDateRange(@Nullable DateRangeParam theDateRangeParam, @Nullable Date theStartInclusive, @Nullable Date theEndExclusive) { 039 if (theStartInclusive == null && theEndExclusive == null) { 040 return theDateRangeParam; 041 } 042 DateRangeParam result = theDateRangeParam==null?new DateRangeParam():new DateRangeParam(theDateRangeParam); 043 044 if (theStartInclusive != null) { 045 Date inputStart = result.getLowerBoundAsInstant(); 046 if (theDateRangeParam == null || inputStart == null || inputStart.before(theStartInclusive)) { 047 result.setLowerBoundInclusive(theStartInclusive); 048 } 049 } 050 if (theEndExclusive != null) { 051 Date inputEnd = result.getUpperBound() == null? null : result.getUpperBound().getValue(); 052 if (theDateRangeParam == null || inputEnd == null || inputEnd.after(theEndExclusive)) { 053 result.setUpperBoundExclusive(theEndExclusive); 054 } 055 } 056 057 return result; 058 } 059 060}