1 /* 2 * Copyright 2001-2007 Stephen Colebourne 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package org.joda.time.field; 17 18 import org.joda.time.Chronology; 19 import org.joda.time.DateTimeField; 20 21 /** 22 * Converts a strict DateTimeField into a lenient one. By being lenient, the 23 * set method accepts out of bounds values, performing an addition instead. 24 * <p> 25 * LenientDateTimeField is thread-safe and immutable. 26 * 27 * @author Brian S O'Neill 28 * @see org.joda.time.chrono.LenientChronology 29 * @see StrictDateTimeField 30 * @since 1.0 31 */ 32 public class LenientDateTimeField extends DelegatedDateTimeField { 33 34 private static final long serialVersionUID = 8714085824173290599L; 35 36 private final Chronology iBase; 37 38 /** 39 * Returns a lenient version of the given field. If it is already lenient, 40 * then it is returned as-is. Otherwise, a new LenientDateTimeField is 41 * returned. 42 */ 43 public static DateTimeField getInstance(DateTimeField field, Chronology base) { 44 if (field == null) { 45 return null; 46 } 47 if (field instanceof StrictDateTimeField) { 48 field = ((StrictDateTimeField)field).getWrappedField(); 49 } 50 if (field.isLenient()) { 51 return field; 52 } 53 return new LenientDateTimeField(field, base); 54 } 55 56 protected LenientDateTimeField(DateTimeField field, Chronology base) { 57 super(field); 58 iBase = base; 59 } 60 61 public final boolean isLenient() { 62 return true; 63 } 64 65 /** 66 * Set values which may be out of bounds by adding the difference between 67 * the new value and the current value. 68 */ 69 public long set(long instant, int value) { 70 // lenient needs to handle time zone chronologies 71 // so we do the calculation using local milliseconds 72 long localInstant = iBase.getZone().convertUTCToLocal(instant); 73 long difference = FieldUtils.safeSubtract(value, get(instant)); 74 localInstant = getType().getField(iBase.withUTC()).add(localInstant, difference); 75 return iBase.getZone().convertLocalToUTC(localInstant, false, instant); 76 } 77 }