Debian Codegraph @

src/main/org/h2/value/ValueDate.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.value;
7
8 import org.h2.api.ErrorCode;
9 import org.h2.engine.CastDataProvider;
10 import org.h2.message.DbException;
11 import org.h2.util.DateTimeUtils;
12
13 /**
14 * Implementation of the DATE data type.
15 */
16 public final class ValueDate extends Value {
17
18 /**
19 * The default precision and display size of the textual representation of a date.
20 * Example: 2000-01-02
21 */
22 public static final int PRECISION = 10;
23
24 private final long dateValue;
25
26 private ValueDate(long dateValue) {
27 if (dateValue < DateTimeUtils.MIN_DATE_VALUE || dateValue > DateTimeUtils.MAX_DATE_VALUE) {
28 throw new IllegalArgumentException("dateValue out of range " + dateValue);
29 }
30 this.dateValue = dateValue;
31 }
32
33 /**
34 * Get or create a date value for the given date.
35 *
36 * @param dateValue the date value
37 * @return the value
38 */
39 public static ValueDate fromDateValue(long dateValue) {
40 return (ValueDate) Value.cache(new ValueDate(dateValue));
41 }
42
43 /**
44 * Parse a string to a ValueDate.
45 *
46 * @param s the string to parse
47 * @return the date
48 */
49 public static ValueDate parse(String s) {
50 try {
51 return fromDateValue(DateTimeUtils.parseDateValue(s, 0, s.length()));
52 } catch (Exception e) {
53 throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2,
54 e, "DATE", s);
55 }
56 }
57
58 public long getDateValue() {
59 return dateValue;
60 }
61
62 @Override
63 public TypeInfo getType() {
64 return TypeInfo.TYPE_DATE;
65 }
66
67 @Override
68 public int getValueType() {
69 return DATE;
70 }
71
72 @Override
73 public String getString() {
74 return DateTimeUtils.appendDate(new StringBuilder(PRECISION), dateValue).toString();
75 }
76
77 @Override
78 public StringBuilder getSQL(StringBuilder builder, int sqlFlags) {
79 return DateTimeUtils.appendDate(builder.append("DATE '"), dateValue).append('\'');
80 }
81
82 @Override
83 public int compareTypeSafe(Value o, CompareMode mode, CastDataProvider provider) {
84 return Long.compare(dateValue, ((ValueDate) o).dateValue);
85 }
86
87 @Override
88 public boolean equals(Object other) {
89 return this == other || other instanceof ValueDate && dateValue == ((ValueDate) other).dateValue;
90 }
91
92 @Override
93 public int hashCode() {
94 return (int) (dateValue ^ (dateValue >>> 32));
95 }
96
97 }