Java Code Examples for java.time.LocalDate#ofEpochDay()

The following examples show how to use java.time.LocalDate#ofEpochDay() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocalDateUtils.java    From Strata with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a number of days to the date.
 * <p>
 * Faster than the JDK method.
 * 
 * @param date  the date to add to
 * @param daysToAdd  the days to add
 * @return the new date
 */
static LocalDate plusDays(LocalDate date, int daysToAdd) {
  if (daysToAdd == 0) {
    return date;
  }
  // add the days to the current day-of-month
  // if it is guaranteed to be in this month or the next month then fast path it
  // (59th Jan is 28th Feb, 59th Feb is 31st Mar)
  long dom = date.getDayOfMonth() + daysToAdd;
  if (dom > 0 && dom <= 59) {
    int monthLen = date.lengthOfMonth();
    int month = date.getMonthValue();
    int year = date.getYear();
    if (dom <= monthLen) {
      return LocalDate.of(year, month, (int) dom);
    } else if (month < 12) {
      return LocalDate.of(year, month + 1, (int) (dom - monthLen));
    } else {
      return LocalDate.of(year + 1, 1, (int) (dom - monthLen));
    }
  }
  long mjDay = Math.addExact(date.toEpochDay(), daysToAdd);
  return LocalDate.ofEpochDay(mjDay);
}
 
Example 2
Source File: LocalDateTest.java    From java-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * 程序执行入口.
 *
 * @param args 命令行参数
 */
public static void main(String[] args) {

	LocalDate today = LocalDate.now(); // |\longremark{获取当前日期}|
	System.out.println("Current Date=" + today);

	LocalDate firstDay2016 = LocalDate.of(2016, 1, 1); // |\longremark{给定年月日创建特定日期对象}|
	System.out.println("Specific Date=" + firstDay2016);


	//LocalDate feb29_2014 = LocalDate.of(2014, Month.FEBRUARY, 29); // |\longremark{给定日期不合法}|
	//Current date in "Asia/Shanghai", you can get it from ZoneId javadoc
	LocalDate todayShanghai = LocalDate.now(ZoneId.of("Asia/Shanghai")); // |\longremark{根据时区获取当前日期}|
	System.out.println("Current Date in CST=" + todayShanghai);


	//LocalDate todayIST = LocalDate.now(ZoneId.of("IST")); // |\longremark{给定时区不合法}|
	LocalDate dateFromBase = LocalDate.ofEpochDay(365); // |\longremark{从1970-1-1开始计算}|
	System.out.println("365th day from base date= " + dateFromBase);

	LocalDate hundredDay2016 = LocalDate.ofYearDay(2016, 100); // |\longremark{从给定年份开始计算}|
	System.out.println("100th day of 2016=" + hundredDay2016);

	LocalDate one = LocalDate.parse("2016-11-21"); //|\longremark{将字符串解析为LocalDate对象}|
	LocalDate two = LocalDate.parse("2016-11-22");
	System.out.println("2016-11-21 parsed to LocalDate = " + one);
	System.out.println("2016-11-21 < 2016-11-22 ? " + one.isBefore(two));
	System.out.println("2016-11-21 < 2016-11-21 ? " + one.isBefore(one));
	System.out.println("2016-11-22 > 2016-11-21 ? " + two.isAfter(one));
}
 
Example 3
Source File: TemporalQueries.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public LocalDate queryFrom(TemporalAccessor temporal) {
    if (temporal.isSupported(EPOCH_DAY)) {
        return LocalDate.ofEpochDay(temporal.getLong(EPOCH_DAY));
    }
    return null;
}
 
Example 4
Source File: LocalDateType.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(ValueFields valueFields) {
    Long longValue = valueFields.getLongValue();
    if (longValue != null) {
        return LocalDate.ofEpochDay(longValue);
    }
    return null;
}
 
Example 5
Source File: CqlMapper.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Override
LocalDate decodeInternal(ByteBuffer input) {
  if (input == null || input.remaining() == 0) return null;
  int unsigned = cint.decode(input);
  int signed = unsigned + Integer.MIN_VALUE;
  return LocalDate.ofEpochDay(signed);
}
 
Example 6
Source File: TimeDependentFilteringTest.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
private static LocalDate randomDate() {
  Random random = new Random();
  int minDay = (int) LocalDate.of(2000, 1, 1).toEpochDay();
  int maxDay = (int) LocalDate.of(2016, 1, 1).toEpochDay();
  long randomDay = minDay + random.nextInt(maxDay - minDay);
  return LocalDate.ofEpochDay(randomDay);
}
 
Example 7
Source File: LocalDateDeserializer.java    From jackson-modules-java8 with Apache License 2.0 4 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasToken(JsonToken.VALUE_STRING)) {
        String string = parser.getText().trim();
        if (string.length() == 0) {
            if (!isLenient()) {
                return _failForNotLenient(parser, context, JsonToken.VALUE_STRING);
            }
            return null;
        }
        // as per [datatype-jsr310#37], only check for optional (and, incorrect...) time marker 'T'
        // if we are using default formatter
        DateTimeFormatter format = _formatter;
        try {
            if (format == DEFAULT_FORMATTER) {
                // JavaScript by default includes time in JSON serialized Dates (UTC/ISO instant format).
                if (string.length() > 10 && string.charAt(10) == 'T') {
                   if (string.endsWith("Z")) {
                       return LocalDateTime.ofInstant(Instant.parse(string), ZoneOffset.UTC).toLocalDate();
                   } else {
                       return LocalDate.parse(string, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                   }
                }
            }
            return LocalDate.parse(string, format);
        } catch (DateTimeException e) {
            return _handleDateTimeFormatException(context, e, format, string);
        }
    }
    if (parser.isExpectedStartArrayToken()) {
        JsonToken t = parser.nextToken();
        if (t == JsonToken.END_ARRAY) {
            return null;
        }
        if (context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
                && (t == JsonToken.VALUE_STRING || t==JsonToken.VALUE_EMBEDDED_OBJECT)) {
            final LocalDate parsed = deserialize(parser, context);
            if (parser.nextToken() != JsonToken.END_ARRAY) {
                handleMissingEndArrayForSingle(parser, context);
            }
            return parsed;            
        }
        if (t == JsonToken.VALUE_NUMBER_INT) {
            int year = parser.getIntValue();
            int month = parser.nextIntValue(-1);
            int day = parser.nextIntValue(-1);
            
            if (parser.nextToken() != JsonToken.END_ARRAY) {
                throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
                        "Expected array to end");
            }
            return LocalDate.of(year, month, day);
        }
        context.reportInputMismatch(handledType(),
                "Unexpected token (%s) within Array, expected VALUE_NUMBER_INT",
                t);
    }
    if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
        return (LocalDate) parser.getEmbeddedObject();
    }
    // 06-Jan-2018, tatu: Is this actually safe? Do users expect such coercion?
    if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
        // issue 58 - also check for NUMBER_INT, which needs to be specified when serializing.
        if (_shape == JsonFormat.Shape.NUMBER_INT || isLenient()) {
            return LocalDate.ofEpochDay(parser.getLongValue());
        }
        return _failForNotLenient(parser, context, JsonToken.VALUE_STRING);
    }
    return _handleUnexpectedToken(context, parser, "Expected array or string.");
}
 
Example 8
Source File: TCKLocalDate.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofEpochDay_aboveMax() {
    LocalDate.ofEpochDay(MAX_VALID_EPOCHDAYS + 1);
}
 
Example 9
Source File: TCKLocalDate.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofEpochDay_belowMin() {
    LocalDate.ofEpochDay(MIN_VALID_EPOCHDAYS - 1);
}
 
Example 10
Source File: TCKLocalDate.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofEpochDay_aboveMax() {
    LocalDate.ofEpochDay(MAX_VALID_EPOCHDAYS + 1);
}
 
Example 11
Source File: RelNodeConvertor.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
public static Object unWrapper(RexLiteral rexLiteral) {
    if (rexLiteral.isNull()) {
        return null;
    }
    RelDataType type = rexLiteral.getType();
    SqlTypeName sqlTypeName = type.getSqlTypeName();
    switch (sqlTypeName) {
        case BOOLEAN:
        case SMALLINT:
        case TINYINT:
        case INTEGER:
        case BIGINT:
        case DECIMAL:
        case FLOAT:
        case REAL:
        case DOUBLE:
            return rexLiteral.getValue();
        case DATE: {
            Integer valueAs = (Integer) rexLiteral.getValue4();
            return LocalDate.ofEpochDay(valueAs);
        }
        case TIME: {
            Integer value = (Integer) rexLiteral.getValue4();
            return LocalTime.ofNanoOfDay(TimeUnit.MILLISECONDS.toNanos(value));
        }
        case TIME_WITH_LOCAL_TIME_ZONE:
            break;
        case TIMESTAMP:
            String s = rexLiteral.toString();
            DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                    .parseCaseInsensitive()
                    .append(ISO_LOCAL_DATE)
                    .appendLiteral(' ')
                    .append(ISO_LOCAL_TIME)
                    .toFormatter();
            return LocalDateTime.parse(s, dateTimeFormatter);
        case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
            break;
        case INTERVAL_YEAR:
            break;
        case INTERVAL_YEAR_MONTH:
            break;
        case INTERVAL_MONTH:
            break;
        case INTERVAL_DAY:
            break;
        case INTERVAL_DAY_HOUR:
            break;
        case INTERVAL_DAY_MINUTE:
            break;
        case INTERVAL_DAY_SECOND:
            break;
        case INTERVAL_HOUR:
            break;
        case INTERVAL_HOUR_MINUTE:
            break;
        case INTERVAL_HOUR_SECOND:
            break;
        case INTERVAL_MINUTE:
            break;
        case INTERVAL_MINUTE_SECOND:
            break;
        case INTERVAL_SECOND:
            break;
        case CHAR:
        case VARCHAR:
            return ((NlsString) rexLiteral.getValue()).getValue();
        case BINARY:
        case VARBINARY:
            return ((org.apache.calcite.avatica.util.ByteString) rexLiteral.getValue()).getBytes();
        case NULL:
            return null;
        case ANY:
            break;
        case SYMBOL:
            break;
        case MULTISET:
            break;
        case ARRAY:
            break;
        case MAP:
            break;
        case DISTINCT:
            break;
        case STRUCTURED:
            break;
        case ROW:
            break;
        case OTHER:
            break;
        case CURSOR:
            break;
        case COLUMN_LIST:
            break;
        case DYNAMIC_STAR:
            break;
        case GEOMETRY:
            break;
    }
    throw new UnsupportedOperationException();
}
 
Example 12
Source File: ArrowResultUtil.java    From snowflake-jdbc with Apache License 2.0 2 votes vote down vote up
/**
 * new method to get Date from integer
 *
 * @param day
 * @return Date
 */
public static Date getDate(int day)
{
  LocalDate localDate = LocalDate.ofEpochDay(day);
  return Date.valueOf(localDate);
}
 
Example 13
Source File: ThaiBuddhistChronology.java    From JDKSourceCode1.8 with MIT License 2 votes vote down vote up
/**
 * Obtains a local date in the Thai Buddhist calendar system from the epoch-day.
 *
 * @param epochDay  the epoch day
 * @return the Thai Buddhist local date, not null
 * @throws DateTimeException if unable to create the date
 */
@Override  // override with covariant return type
public ThaiBuddhistDate dateEpochDay(long epochDay) {
    return new ThaiBuddhistDate(LocalDate.ofEpochDay(epochDay));
}
 
Example 14
Source File: ThaiBuddhistChronology.java    From dragonwell8_jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtains a local date in the Thai Buddhist calendar system from the epoch-day.
 *
 * @param epochDay  the epoch day
 * @return the Thai Buddhist local date, not null
 * @throws DateTimeException if unable to create the date
 */
@Override  // override with covariant return type
public ThaiBuddhistDate dateEpochDay(long epochDay) {
    return new ThaiBuddhistDate(LocalDate.ofEpochDay(epochDay));
}
 
Example 15
Source File: MinguoChronology.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtains a local date in the Minguo calendar system from the epoch-day.
 *
 * @param epochDay  the epoch day
 * @return the Minguo local date, not null
 * @throws DateTimeException if unable to create the date
 */
@Override  // override with covariant return type
public MinguoDate dateEpochDay(long epochDay) {
    return new MinguoDate(LocalDate.ofEpochDay(epochDay));
}
 
Example 16
Source File: IsoChronology.java    From openjdk-8-source with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtains an ISO local date from the epoch-day.
 * <p>
 * This is equivalent to {@link LocalDate#ofEpochDay(long)}.
 *
 * @param epochDay  the epoch day
 * @return the ISO local date, not null
 * @throws DateTimeException if unable to create the date
 */
@Override  // override with covariant return type
public LocalDate dateEpochDay(long epochDay) {
    return LocalDate.ofEpochDay(epochDay);
}
 
Example 17
Source File: MinguoChronology.java    From jdk1.8-source-analysis with Apache License 2.0 2 votes vote down vote up
/**
 * Obtains a local date in the Minguo calendar system from the epoch-day.
 *
 * @param epochDay  the epoch day
 * @return the Minguo local date, not null
 * @throws DateTimeException if unable to create the date
 */
@Override  // override with covariant return type
public MinguoDate dateEpochDay(long epochDay) {
    return new MinguoDate(LocalDate.ofEpochDay(epochDay));
}
 
Example 18
Source File: ThaiBuddhistChronology.java    From jdk8u_jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtains a local date in the Thai Buddhist calendar system from the epoch-day.
 *
 * @param epochDay  the epoch day
 * @return the Thai Buddhist local date, not null
 * @throws DateTimeException if unable to create the date
 */
@Override  // override with covariant return type
public ThaiBuddhistDate dateEpochDay(long epochDay) {
    return new ThaiBuddhistDate(LocalDate.ofEpochDay(epochDay));
}
 
Example 19
Source File: MinguoChronology.java    From jdk8u_jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Obtains a local date in the Minguo calendar system from the epoch-day.
 *
 * @param epochDay  the epoch day
 * @return the Minguo local date, not null
 * @throws DateTimeException if unable to create the date
 */
@Override  // override with covariant return type
public MinguoDate dateEpochDay(long epochDay) {
    return new MinguoDate(LocalDate.ofEpochDay(epochDay));
}
 
Example 20
Source File: IsoChronology.java    From JDKSourceCode1.8 with MIT License 2 votes vote down vote up
/**
 * Obtains an ISO local date from the epoch-day.
 * <p>
 * This is equivalent to {@link LocalDate#ofEpochDay(long)}.
 *
 * @param epochDay  the epoch day
 * @return the ISO local date, not null
 * @throws DateTimeException if unable to create the date
 */
@Override  // override with covariant return type
public LocalDate dateEpochDay(long epochDay) {
    return LocalDate.ofEpochDay(epochDay);
}