001 /*
002 * Copyright 2001-2007 Stephen Colebourne
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package org.joda.time.field;
017
018 import org.joda.time.Chronology;
019 import org.joda.time.DateTimeField;
020
021 /**
022 * Converts a strict DateTimeField into a lenient one. By being lenient, the
023 * set method accepts out of bounds values, performing an addition instead.
024 * <p>
025 * LenientDateTimeField is thread-safe and immutable.
026 *
027 * @author Brian S O'Neill
028 * @see org.joda.time.chrono.LenientChronology
029 * @see StrictDateTimeField
030 * @since 1.0
031 */
032 public class LenientDateTimeField extends DelegatedDateTimeField {
033
034 private static final long serialVersionUID = 8714085824173290599L;
035
036 private final Chronology iBase;
037
038 /**
039 * Returns a lenient version of the given field. If it is already lenient,
040 * then it is returned as-is. Otherwise, a new LenientDateTimeField is
041 * returned.
042 */
043 public static DateTimeField getInstance(DateTimeField field, Chronology base) {
044 if (field == null) {
045 return null;
046 }
047 if (field instanceof StrictDateTimeField) {
048 field = ((StrictDateTimeField)field).getWrappedField();
049 }
050 if (field.isLenient()) {
051 return field;
052 }
053 return new LenientDateTimeField(field, base);
054 }
055
056 protected LenientDateTimeField(DateTimeField field, Chronology base) {
057 super(field);
058 iBase = base;
059 }
060
061 public final boolean isLenient() {
062 return true;
063 }
064
065 /**
066 * Set values which may be out of bounds by adding the difference between
067 * the new value and the current value.
068 */
069 public long set(long instant, int value) {
070 // lenient needs to handle time zone chronologies
071 // so we do the calculation using local milliseconds
072 long localInstant = iBase.getZone().convertUTCToLocal(instant);
073 long difference = FieldUtils.safeSubtract(value, get(instant));
074 localInstant = getType().getField(iBase.withUTC()).add(localInstant, difference);
075 return iBase.getZone().convertLocalToUTC(localInstant, false, instant);
076 }
077 }