Search in sources :

Example 96 with ZoneOffset

use of java.time.ZoneOffset in project graylog2-server by Graylog2.

the class DateTimeConverter method convertToDateTime.

public static DateTime convertToDateTime(@Nonnull Object value) {
    if (value instanceof DateTime) {
        return (DateTime) value;
    }
    if (value instanceof Date) {
        return new DateTime(value, DateTimeZone.UTC);
    } else if (value instanceof ZonedDateTime) {
        final DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TimeZone.getTimeZone(((ZonedDateTime) value).getZone()));
        return new DateTime(Date.from(((ZonedDateTime) value).toInstant()), dateTimeZone);
    } else if (value instanceof OffsetDateTime) {
        return new DateTime(Date.from(((OffsetDateTime) value).toInstant()), DateTimeZone.UTC);
    } else if (value instanceof LocalDateTime) {
        final LocalDateTime localDateTime = (LocalDateTime) value;
        final ZoneId defaultZoneId = ZoneId.systemDefault();
        final ZoneOffset offset = defaultZoneId.getRules().getOffset(localDateTime);
        return new DateTime(Date.from(localDateTime.toInstant(offset)));
    } else if (value instanceof LocalDate) {
        final LocalDate localDate = (LocalDate) value;
        final LocalDateTime localDateTime = localDate.atStartOfDay();
        final ZoneId defaultZoneId = ZoneId.systemDefault();
        final ZoneOffset offset = defaultZoneId.getRules().getOffset(localDateTime);
        return new DateTime(Date.from(localDateTime.toInstant(offset)));
    } else if (value instanceof Instant) {
        return new DateTime(Date.from((Instant) value), DateTimeZone.UTC);
    } else if (value instanceof String) {
        return ES_DATE_FORMAT_FORMATTER.parseDateTime((String) value);
    } else {
        throw new IllegalArgumentException("Value of invalid type <" + value.getClass().getSimpleName() + "> provided");
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) ZoneId(java.time.ZoneId) ZonedDateTime(java.time.ZonedDateTime) OffsetDateTime(java.time.OffsetDateTime) Instant(java.time.Instant) LocalDate(java.time.LocalDate) ZonedDateTime(java.time.ZonedDateTime) DateTime(org.joda.time.DateTime) LocalDateTime(java.time.LocalDateTime) OffsetDateTime(java.time.OffsetDateTime) Date(java.util.Date) LocalDate(java.time.LocalDate) DateTimeZone(org.joda.time.DateTimeZone) ZoneOffset(java.time.ZoneOffset)

Example 97 with ZoneOffset

use of java.time.ZoneOffset in project CoreNLP by stanfordnlp.

the class SUTime method parseInstant.

/**
 * Try parsing a given string into an {@link Instant} in as many ways as we know how.
 * Dates will be normalized to the start of their days.
 *
 * @param value The instant we are parsing.
 * @param timezone The timezone, if none is given in the instant.
 *
 * @return An instant corresponding to the value, if it could be parsed.
 */
public static Optional<java.time.Instant> parseInstant(String value, Optional<ZoneId> timezone) {
    for (java.time.format.DateTimeFormatter formatter : DATE_TIME_FORMATS) {
        try {
            TemporalAccessor datetime = formatter.parse(value);
            ZoneId parsedTimezone = datetime.query(TemporalQueries.zoneId());
            ZoneOffset parsedOffset = datetime.query(TemporalQueries.offset());
            if (parsedTimezone != null) {
                return Optional.of(java.time.Instant.from(datetime));
            } else if (parsedOffset != null) {
                try {
                    return Optional.of(java.time.Instant.ofEpochSecond(datetime.getLong(ChronoField.INSTANT_SECONDS)));
                } catch (UnsupportedTemporalTypeException e) {
                    return Optional.of(java.time.LocalDate.of(datetime.get(ChronoField.YEAR), datetime.get(ChronoField.MONTH_OF_YEAR), datetime.get(ChronoField.DAY_OF_MONTH)).atStartOfDay().toInstant(parsedOffset));
                }
            } else {
                if (timezone.isPresent()) {
                    java.time.Instant reference = java.time.LocalDate.of(datetime.get(ChronoField.YEAR), datetime.get(ChronoField.MONTH_OF_YEAR), datetime.get(ChronoField.DAY_OF_MONTH)).atStartOfDay().toInstant(ZoneOffset.UTC);
                    ZoneOffset currentOffsetForMyZone = timezone.get().getRules().getOffset(reference);
                    try {
                        return Optional.of(java.time.LocalDateTime.of(datetime.get(ChronoField.YEAR), datetime.get(ChronoField.MONTH_OF_YEAR), datetime.get(ChronoField.DAY_OF_MONTH), datetime.get(ChronoField.HOUR_OF_DAY), datetime.get(ChronoField.MINUTE_OF_HOUR), datetime.get(ChronoField.SECOND_OF_MINUTE)).toInstant(currentOffsetForMyZone));
                    } catch (UnsupportedTemporalTypeException e) {
                        return Optional.of(java.time.LocalDate.of(datetime.get(ChronoField.YEAR), datetime.get(ChronoField.MONTH_OF_YEAR), datetime.get(ChronoField.DAY_OF_MONTH)).atStartOfDay().toInstant(currentOffsetForMyZone));
                    }
                }
            }
        } catch (DateTimeParseException ignored) {
        }
    }
    return Optional.empty();
}
Also used : DateTimeParseException(java.time.format.DateTimeParseException) TemporalAccessor(java.time.temporal.TemporalAccessor) ZoneId(java.time.ZoneId) UnsupportedTemporalTypeException(java.time.temporal.UnsupportedTemporalTypeException) ZoneOffset(java.time.ZoneOffset)

Example 98 with ZoneOffset

use of java.time.ZoneOffset in project sonarqube by SonarSource.

the class GithubAppSecurityImpl method createAppToken.

@Override
public AppToken createAppToken(long appId, String privateKey) {
    Algorithm algorithm = readApplicationPrivateKey(appId, privateKey);
    LocalDateTime now = LocalDateTime.now(clock);
    // Expiration period is configurable and could be greater if needed.
    // See https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app
    LocalDateTime expiresAt = now.plus(AppToken.EXPIRATION_PERIOD_IN_MINUTES, ChronoUnit.MINUTES);
    ZoneOffset offset = clock.getZone().getRules().getOffset(now);
    Date nowDate = Date.from(now.toInstant(offset));
    Date expiresAtDate = Date.from(expiresAt.toInstant(offset));
    JWTCreator.Builder builder = JWT.create().withIssuer(String.valueOf(appId)).withIssuedAt(nowDate).withExpiresAt(expiresAtDate);
    return new AppToken(builder.sign(algorithm));
}
Also used : LocalDateTime(java.time.LocalDateTime) JWTCreator(com.auth0.jwt.JWTCreator) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) ZoneOffset(java.time.ZoneOffset)

Example 99 with ZoneOffset

use of java.time.ZoneOffset in project drools by kiegroup.

the class TypeUtil method formatValue.

public static String formatValue(final Object val, final boolean wrapForCodeUsage) {
    if (val instanceof String) {
        return formatString(val.toString(), wrapForCodeUsage);
    } else if (val instanceof LocalDate) {
        return formatDate((LocalDate) val, wrapForCodeUsage);
    } else if (val instanceof LocalTime || val instanceof OffsetTime) {
        return formatTimeString(TimeFunction.FEEL_TIME.format((TemporalAccessor) val), wrapForCodeUsage);
    } else if (val instanceof LocalDateTime || val instanceof OffsetDateTime) {
        return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), wrapForCodeUsage);
    } else if (val instanceof ZonedDateTime) {
        TemporalAccessor ta = (TemporalAccessor) val;
        ZoneId zone = ta.query(TemporalQueries.zone());
        if (!(zone instanceof ZoneOffset)) {
            // it is a ZoneRegion
            return formatDateTimeString(DateAndTimeFunction.REGION_DATETIME_FORMATTER.format((TemporalAccessor) val), wrapForCodeUsage);
        } else {
            return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), wrapForCodeUsage);
        }
    } else if (val instanceof Duration) {
        return formatDuration((Duration) val, wrapForCodeUsage);
    } else if (val instanceof ChronoPeriod) {
        return formatPeriod((ChronoPeriod) val, wrapForCodeUsage);
    } else if (val instanceof TemporalAccessor) {
        TemporalAccessor ta = (TemporalAccessor) val;
        if (ta.query(TemporalQueries.localDate()) == null && ta.query(TemporalQueries.localTime()) != null && ta.query(TemporalQueries.zoneId()) != null) {
            return formatTimeString(TimeFunction.FEEL_TIME.format((TemporalAccessor) val), wrapForCodeUsage);
        } else {
            return String.valueOf(val);
        }
    } else if (val instanceof List) {
        return formatList((List) val, wrapForCodeUsage);
    } else if (val instanceof Range) {
        return formatRange((Range) val, wrapForCodeUsage);
    } else if (val instanceof Map) {
        return formatContext((Map) val, wrapForCodeUsage);
    } else {
        return String.valueOf(val);
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) ChronoPeriod(java.time.chrono.ChronoPeriod) TemporalAccessor(java.time.temporal.TemporalAccessor) LocalTime(java.time.LocalTime) ZoneId(java.time.ZoneId) Duration(java.time.Duration) Range(org.kie.dmn.feel.runtime.Range) LocalDate(java.time.LocalDate) ZoneOffset(java.time.ZoneOffset) OffsetDateTime(java.time.OffsetDateTime) ZonedDateTime(java.time.ZonedDateTime) OffsetTime(java.time.OffsetTime) List(java.util.List) Map(java.util.Map)

Example 100 with ZoneOffset

use of java.time.ZoneOffset in project tck by dmn-tck.

the class CamundaTCKTest method transformDateTime.

private Object transformDateTime(final XMLGregorianCalendar cal) {
    final int nanoSeconds = Optional.ofNullable(cal.getFractionalSecond()).map(fraction -> fraction.movePointRight(9).intValue()).orElse(0);
    final int timezone = cal.getTimezone();
    final boolean hasOffset = timezone != DatatypeConstants.FIELD_UNDEFINED;
    final ZoneOffset offset = hasOffset ? ZoneOffset.ofTotalSeconds(timezone * 60) : null;
    final QName type = cal.getXMLSchemaType();
    if (type == DatatypeConstants.DATE) {
        return LocalDate.of(cal.getYear(), cal.getMonth(), cal.getDay());
    }
    if (type == DatatypeConstants.TIME) {
        final LocalTime localTime = LocalTime.of(cal.getHour(), cal.getMinute(), cal.getSecond(), nanoSeconds);
        if (hasOffset) {
            return OffsetTime.of(localTime, offset);
        } else {
            return localTime;
        }
    }
    if (type == DatatypeConstants.DATETIME) {
        final LocalDateTime locateDateTime = LocalDateTime.of(cal.getYear(), cal.getMonth(), cal.getDay(), cal.getHour(), cal.getMinute(), cal.getSecond(), nanoSeconds);
        if (hasOffset) {
            return OffsetDateTime.of(locateDateTime, offset).toZonedDateTime();
        } else {
            return locateDateTime;
        }
    }
    throw new RuntimeException(String.format("Unexpected calendar value: '%s'", cal));
}
Also used : DmnDecision(org.camunda.bpm.dmn.engine.DmnDecision) Arrays(java.util.Arrays) DmnTckSuite(org.omg.dmn.tck.runner.junit4.DmnTckSuite) DmnTckVendorTestSuite(org.omg.dmn.tck.runner.junit4.DmnTckVendorTestSuite) URL(java.net.URL) LocalDateTime(java.time.LocalDateTime) RunWith(org.junit.runner.RunWith) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Result(org.omg.dmn.tck.runner.junit4.TestResult.Result) ArrayList(java.util.ArrayList) BigDecimal(java.math.BigDecimal) Duration(javax.xml.datatype.Duration) TestSuiteContext(org.omg.dmn.tck.runner.junit4.TestSuiteContext) Map(java.util.Map) Node(org.w3c.dom.Node) LocalTime(java.time.LocalTime) DatatypeConstants(javax.xml.datatype.DatatypeConstants) BigInteger(java.math.BigInteger) ZoneOffset(java.time.ZoneOffset) DmnEngine(org.camunda.bpm.dmn.engine.DmnEngine) OffsetTime(java.time.OffsetTime) Period(java.time.Period) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) MathContext(java.math.MathContext) DefaultDmnEngineConfiguration(org.camunda.bpm.dmn.engine.impl.DefaultDmnEngineConfiguration) JAXBElement(javax.xml.bind.JAXBElement) Description(org.junit.runner.Description) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) Collectors(java.util.stream.Collectors) File(java.io.File) TestResult(org.omg.dmn.tck.runner.junit4.TestResult) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) LocalDate(java.time.LocalDate) DmnDecisionResult(org.camunda.bpm.dmn.engine.DmnDecisionResult) Component(org.omg.dmn.tck.marshaller._20160719.ValueType.Component) Optional(java.util.Optional) ValueType(org.omg.dmn.tck.marshaller._20160719.ValueType) QName(javax.xml.namespace.QName) Comparator(java.util.Comparator) TestCases(org.omg.dmn.tck.marshaller._20160719.TestCases) ResultNode(org.omg.dmn.tck.marshaller._20160719.TestCases.TestCase.ResultNode) LocalDateTime(java.time.LocalDateTime) LocalTime(java.time.LocalTime) QName(javax.xml.namespace.QName) ZoneOffset(java.time.ZoneOffset)

Aggregations

ZoneOffset (java.time.ZoneOffset)201 Test (org.junit.Test)51 LocalDateTime (java.time.LocalDateTime)36 ZoneId (java.time.ZoneId)36 Test (org.testng.annotations.Test)35 ZonedDateTime (java.time.ZonedDateTime)27 LocalTime (java.time.LocalTime)25 ZoneRules (java.time.zone.ZoneRules)23 OffsetDateTime (java.time.OffsetDateTime)20 Instant (java.time.Instant)17 LocalDate (java.time.LocalDate)16 TemporalAccessor (java.time.temporal.TemporalAccessor)11 ZoneOffsetTransition (java.time.zone.ZoneOffsetTransition)11 OffsetTime (java.time.OffsetTime)10 DateTimeFormatter (java.time.format.DateTimeFormatter)10 ArrayList (java.util.ArrayList)8 UseDataProvider (com.tngtech.java.junit.dataprovider.UseDataProvider)7 List (java.util.List)6 BigDecimal (java.math.BigDecimal)5 Clock (java.time.Clock)5