0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018 package org.apache.spark.unsafe.types;
0019
0020 import org.apache.spark.annotation.Unstable;
0021
0022 import java.io.Serializable;
0023 import java.math.BigDecimal;
0024 import java.time.Duration;
0025 import java.time.Period;
0026 import java.time.temporal.ChronoUnit;
0027 import java.util.Objects;
0028
0029 import static org.apache.spark.sql.catalyst.util.DateTimeConstants.*;
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046 @Unstable
0047 public final class CalendarInterval implements Serializable {
0048
0049
0050 public final int months;
0051 public final int days;
0052 public final long microseconds;
0053
0054
0055
0056
0057
0058 public CalendarInterval(int months, int days, long microseconds) {
0059 this.months = months;
0060 this.days = days;
0061 this.microseconds = microseconds;
0062 }
0063
0064 @Override
0065 public boolean equals(Object o) {
0066 if (this == o) return true;
0067 if (o == null || getClass() != o.getClass()) return false;
0068 CalendarInterval that = (CalendarInterval) o;
0069 return months == that.months &&
0070 days == that.days &&
0071 microseconds == that.microseconds;
0072 }
0073
0074 @Override
0075 public int hashCode() {
0076 return Objects.hash(months, days, microseconds);
0077 }
0078
0079 @Override
0080 public String toString() {
0081 if (months == 0 && days == 0 && microseconds == 0) {
0082 return "0 seconds";
0083 }
0084
0085 StringBuilder sb = new StringBuilder();
0086
0087 if (months != 0) {
0088 appendUnit(sb, months / 12, "years");
0089 appendUnit(sb, months % 12, "months");
0090 }
0091
0092 appendUnit(sb, days, "days");
0093
0094 if (microseconds != 0) {
0095 long rest = microseconds;
0096 appendUnit(sb, rest / MICROS_PER_HOUR, "hours");
0097 rest %= MICROS_PER_HOUR;
0098 appendUnit(sb, rest / MICROS_PER_MINUTE, "minutes");
0099 rest %= MICROS_PER_MINUTE;
0100 if (rest != 0) {
0101 String s = BigDecimal.valueOf(rest, 6).stripTrailingZeros().toPlainString();
0102 sb.append(s).append(" seconds ");
0103 }
0104 }
0105
0106 sb.setLength(sb.length() - 1);
0107 return sb.toString();
0108 }
0109
0110 private void appendUnit(StringBuilder sb, long value, String unit) {
0111 if (value != 0) {
0112 sb.append(value).append(' ').append(unit).append(' ');
0113 }
0114 }
0115
0116
0117
0118
0119
0120
0121 public Period extractAsPeriod() { return Period.of(0, months, days); }
0122
0123
0124
0125
0126
0127
0128
0129 public Duration extractAsDuration() { return Duration.of(microseconds, ChronoUnit.MICROS); }
0130 }