KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > joda > time > field > LenientDateTimeField


1 /*
2  * Copyright 2001-2005 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.DateTimeField;
19
20 /**
21  * Converts a strict DateTimeField into a lenient one. By being lenient, the
22  * set method accepts out of bounds values, performing an addition instead.
23  * <p>
24  * LenientDateTimeField is thread-safe and immutable.
25  *
26  * @author Brian S O'Neill
27  * @see org.joda.time.chrono.LenientChronology
28  * @see StrictDateTimeField
29  * @since 1.0
30  */

31 public class LenientDateTimeField extends DelegatedDateTimeField {
32
33     private static final long serialVersionUID = 8714085824173290599L;
34
35     /**
36      * Returns a lenient version of the given field. If it is already lenient,
37      * then it is returned as-is. Otherwise, a new LenientDateTimeField is
38      * returned.
39      */

40     public static DateTimeField getInstance(DateTimeField field) {
41         if (field == null) {
42             return null;
43         }
44         if (field instanceof StrictDateTimeField) {
45             field = ((StrictDateTimeField)field).getWrappedField();
46         }
47         if (field.isLenient()) {
48             return field;
49         }
50         return new LenientDateTimeField(field);
51     }
52
53     protected LenientDateTimeField(DateTimeField field) {
54         super(field);
55     }
56
57     public final boolean isLenient() {
58         return true;
59     }
60
61     /**
62      * Set values which may be out of bounds. If the value is out of bounds,
63      * the instant is first set to the minimum allowed value, and then the
64      * difference is added.
65      */

66     public long set(long instant, int value) {
67         int min = getMinimumValue(instant);
68         if (value >= min && value < getMaximumValue(instant)) {
69             return super.set(instant, value);
70         }
71         return add(super.set(instant, min), value - min);
72     }
73 }
74
Popular Tags