Java Code Examples for java.time.ZonedDateTime#toEpochSecond()

The following examples show how to use java.time.ZonedDateTime#toEpochSecond() . 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: ElasticsearchFieldResolver.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a date-time string to epoch-milliseconds. The ISO_ZONED_DATE_TIME format will be attempted first,
 * followed by the ISO_LOCAL_DATE_TIME format if the previous one fails. Examples of formats that will work:
 * 1) "2020-05-18T10:15:30.123456789"
 * 2) "2020-05-15T06:50:01.123Z"
 * 3) "2020-05-15T06:49:30.123-05:00".
 * Nanoseconds will be rounded to the nearest millisecond.
 * @param dateTimeValue is the date-time value to be converted to epoch-milliseconds.
 * @return a long value representing the epoch-milliseconds derived from dateTimeValue.
 * @throws DateTimeParseException
 */
private long toEpochMillis(String dateTimeValue)
        throws DateTimeParseException
{
    long epochSeconds;
    double nanoSeconds;

    try {
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeValue,
                DateTimeFormatter.ISO_ZONED_DATE_TIME.withResolverStyle(ResolverStyle.SMART));
        epochSeconds = zonedDateTime.toEpochSecond();
        nanoSeconds = zonedDateTime.getNano();
    }
    catch (DateTimeParseException error) {
        LocalDateTime localDateTime = LocalDateTime.parse(dateTimeValue,
                DateTimeFormatter.ISO_LOCAL_DATE_TIME
                        .withResolverStyle(ResolverStyle.SMART));
        epochSeconds = localDateTime.toEpochSecond(ZoneOffset.UTC);
        nanoSeconds = localDateTime.getNano();
    }

    return epochSeconds * 1000 + Math.round(nanoSeconds / 1000000);
}
 
Example 2
Source File: DateService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public boolean isTrigger(TimeAlert alert, long monitorUpdateRate, ZonedDateTime currentTime) {
    try {
        String timeZone = alert.getTimeZone();
        CronSequenceGenerator cronExpression = getCronExpression(alert.getCron());
        ZonedDateTime zonedCurrentTime = dateTimeService.getZonedDateTime(currentTime.toInstant(), timeZone);
        LocalDateTime startTimeOfTheMonitorInterval = zonedCurrentTime.toLocalDateTime().minus(monitorUpdateRate, ChronoUnit.MILLIS);
        Date startDate = Date.from(startTimeOfTheMonitorInterval.toInstant(currentTime.getOffset()));
        Date nextTime = cronExpression.next(startDate);
        ZonedDateTime zonedNextTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(nextTime.getTime()), currentTime.getZone()).atZone(ZoneId.of(timeZone));
        long interval = (zonedCurrentTime.toEpochSecond() - zonedNextTime.toEpochSecond()) * TimeUtil.SECOND_TO_MILLISEC;

        boolean triggerReady = interval >= 0L && interval < monitorUpdateRate;
        if (triggerReady) {
            LOGGER.info("Time alert '{}' firing at '{}' compared to current time '{}' in timezone '{}'",
                    alert.getName(), zonedNextTime, zonedCurrentTime, timeZone);
        }
        return triggerReady;
    } catch (ParseException e) {
        LOGGER.error("Invalid cron expression '{}', cluster '{}'", e.getMessage(), alert.getCluster().getStackCrn());
        return false;
    }
}
 
Example 3
Source File: FixedHourScheduleTest.java    From Wisp with Apache License 2.0 6 votes vote down vote up
@Test
public void should_calcule_next_execution_from_midday() {
	ZoneId ectZone = ZoneId.of("Europe/Paris");
	ZonedDateTime augustMidday = LocalDate
		.of(2016, 8, 31)
		.atTime(12, 0)
		.atZone(ectZone);
	long midday = augustMidday.toEpochSecond() * 1000;

	assertThat(
		new FixedHourSchedule("12:00:00", ectZone).durationUntilNextExecutionInMillis(midday, null)
	).isEqualTo(0);
	assertThat(
		new FixedHourSchedule("12:00:01", ectZone).durationUntilNextExecutionInMillis(midday, null)
	).isEqualTo(1000);
	assertThat(
		new FixedHourSchedule("11:59:59", ectZone).durationUntilNextExecutionInMillis(midday, null)
	).isEqualTo(24 * 60 * 60 * 1000 - 1000);
	assertThat(
		new FixedHourSchedule("00:00:00", ectZone).durationUntilNextExecutionInMillis(midday, null)
	).isEqualTo(12 * 60 * 60 * 1000);
}
 
Example 4
Source File: TimeUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
 * 设置当前系统时间
 *
 * @param datetime
 * @return
 */
public static boolean setCurrentDateTime(String datetime) {
    ZonedDateTime zdt = getZonedDateTime(datetime, YYYYMMDDHHMMSS);
    if (zdt == null) {
        zdt = getZonedDateTime(datetime, YYYYMMDDHHMM);
    }
    if (zdt == null) {
        zdt = getZonedDateTime(datetime, YYYYMMDDHH);
    }
    if (zdt == null) {
        zdt = getZonedDateTime(datetime, YYYYMMDD);
    }
    if (zdt == null) {
        return false;
    }
    timeOffset = zdt.toEpochSecond() * 1000 - Clock.systemDefaultZone().instant().toEpochMilli();
    return true;
}
 
Example 5
Source File: FixedHourScheduleTest.java    From Wisp with Apache License 2.0 6 votes vote down vote up
@Test
public void should_calcule_next_execution_during_time_change() {
	ZoneId ectZone = ZoneId.of("Europe/Paris");
	ZonedDateTime oneSecBeforeTimeChange = LocalDate
		.of(2016, 10, 30)
		.atTime(1, 59, 59)
		.atZone(ectZone);
	long oneSecBeforeTimeChangeMillis = oneSecBeforeTimeChange.toEpochSecond() * 1000;
	long oneSecAfterTimeChangeMillis = (oneSecBeforeTimeChange.toEpochSecond() + 2) * 1000;

	assertThat(
		new FixedHourSchedule("02:00:00", ectZone)
			.durationUntilNextExecutionInMillis(oneSecBeforeTimeChangeMillis, null)
	).isEqualTo(1000);
	assertThat(
		new FixedHourSchedule("02:00:00", ectZone)
			.durationUntilNextExecutionInMillis(oneSecAfterTimeChangeMillis, null)
	).isEqualTo(25 * 60 * 60 * 1000 - 1000);
}
 
Example 6
Source File: VertxWithRxJavaIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
private static Function<JsonObject, CityAndDayLength> toCityAndDayLength() {
    return json -> {
        ZonedDateTime sunRise = ZonedDateTime.parse(json.getString("sun_rise"));
        ZonedDateTime sunSet = ZonedDateTime.parse(json.getString("sun_set"));
        String cityName = json.getString("title");
        return new CityAndDayLength(
          cityName, sunSet.toEpochSecond() - sunRise.toEpochSecond());
    };
}
 
Example 7
Source File: VertxVaadinRequestUT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Test
public void shouldDelegateGetDateHeader() {
    ZonedDateTime headerValue = LocalDateTime.of(2016, 7, 3, 8, 49, 37)
        .atZone(ZoneId.of("GMT"));
    long longHeaderValue = headerValue.toEpochSecond() * 1000;
    when(httpServerRequest.getHeader(HttpHeaders.IF_MODIFIED_SINCE.toString()))
        .thenReturn(null)
        .thenReturn("Sun, 03 Jul 2016 08:49:37 GMT")
        .thenReturn("Sunday, 03-Jul-16 08:49:37 GMT")
        .thenReturn("Sun Jul  3 08:49:37 2016");
    assertThat(vaadinRequest.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE.toString())).isEqualTo(-1);
    assertThat(vaadinRequest.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE.toString())).isEqualTo(longHeaderValue);
    assertThat(vaadinRequest.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE.toString())).isEqualTo(longHeaderValue);
    assertThat(vaadinRequest.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE.toString())).isEqualTo(longHeaderValue);
}
 
Example 8
Source File: CronScheduleTest.java    From Wisp with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_executed_daily_jobs_twice_a_day() {
	CronSchedule everyMinuteScheduler = CronSchedule.parseQuartzCron("0 0 12 * * ? *");

	ZonedDateTime augustMidday = LocalDate
		.of(2016, 8, 31)
		.atTime(12, 0)
		.atZone(ZoneId.systemDefault());
	long midday = augustMidday.toEpochSecond() * 1000;

	assertThat(everyMinuteScheduler.nextExecutionInMillis(midday-1, 0, null))
	.isEqualTo(midday);
	assertThat(everyMinuteScheduler.nextExecutionInMillis(midday, 0, null))
	.isEqualTo(midday + Duration.ofDays(1).toMillis());
}
 
Example 9
Source File: TestTimestampWithTimeZone.java    From presto with Apache License 2.0 5 votes vote down vote up
private BiFunction<Session, QueryRunner, Object> timestampWithTimeZone(int precision, int year, int month, int day, int hour, int minute, int second, long picoOfSecond, TimeZoneKey timeZoneKey)
{
    return (session, queryRunner) -> {
        ZonedDateTime base = ZonedDateTime.of(year, month, day, hour, minute, second, 0, timeZoneKey.getZoneId());

        long epochMillis = base.toEpochSecond() * MILLISECONDS_PER_SECOND + picoOfSecond / PICOSECONDS_PER_MILLISECOND;
        int picosOfMilli = (int) (picoOfSecond % PICOSECONDS_PER_MILLISECOND);

        return SqlTimestampWithTimeZone.newInstance(precision, epochMillis, picosOfMilli, timeZoneKey);
    };
}
 
Example 10
Source File: NodeHealthEvent.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public long getTimeInMilliseconds() {
    ZonedDateTime time = health.getTime();
    if(time == null) {
        return Long.MIN_VALUE;
    }
    return time.toEpochSecond();
}
 
Example 11
Source File: LeaderElectorTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void nowShouldReturnZonedTimeInUTC() {
  // Given
  final Instant now = Instant.now();
  // When
  final ZonedDateTime result = now();
  // Then
  assertEquals(ZoneOffset.UTC, result.getZone());
  final long delta = result.toEpochSecond() - now.getEpochSecond();
  assertTrue(delta <= 1);
  assertTrue(delta >= 0);
}
 
Example 12
Source File: ZonedDateTimeMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public ValueBuilder<?, ?, ?> toDatastore(Object input) {
  if (input == null) {
    return NullValue.newBuilder();
  }
  ZonedDateTime zonedDateTime = (ZonedDateTime) input;
  long seconds = zonedDateTime.toEpochSecond();
  int nanos = zonedDateTime.getNano();
  long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos);
  return TimestampValue.newBuilder(Timestamp.ofTimeMicroseconds(microseconds));
}
 
Example 13
Source File: OlympicModel2.java    From egads with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void train(final DataSequence data) throws Exception {
    initializeIndices(data, modelStartEpoch);
    
    final long size = data.size();
    ZonedDateTime model_ts = Instant.ofEpochSecond(modelStartEpoch)
            .atZone(zone);
    ZonedDateTime end_ts = model_ts.plus(windowSize, windowUnits);
    int prediction_index = 0;
    final List<WeightedValue> accumulator = Lists.newArrayList();
    
    // start the loop and break once we've filled the model.
    while (true) {
        accumulator.clear();
        for (int i = 0; i < windowTimes.length; i++) {
            if (indices[i] < 0 || indices[i] >= size) {
                continue;
            }
            
            // advance
            windowTimes[i] = windowTimes[i].plus(interval,
                    intervalUnits);
            long interval_end = windowTimes[i].toEpochSecond();
            final List<Double> doubles = Lists.newArrayList();
            long first_ts = -1;
            while (indices[i] < size
                    && data.get(indices[i]).time < interval_end) {
                if (Double.isFinite(data.get(indices[i]).value)) {
                    doubles.add((double) data.get(indices[i]).value);
                }
                if (first_ts < 0) {
                    first_ts = data.get(indices[i]).time;
                }
                indices[i]++;
            }

            if (!doubles.isEmpty()) {
                // TODO - for DST if we jumped back then we may have a
                // period
                // with more than we expect. In that case, depending on the
                // aggregator, we may need to use only part of the data.
                // TODO - potentially other aggregations.
                double sum = 0;
                for (final Double v : doubles) {
                    sum += v;
                }
                accumulator.add(
                        new WeightedValue((sum / doubles.size()), i + 1));
            }
        }

        if (drop_lowest > 0 || drop_highest > 0) {
            if (drop_highest > drop_lowest) {
                WeightedValue.drop(accumulator, drop_highest, true);
                WeightedValue.drop(accumulator, drop_lowest, false);
            } else {
                WeightedValue.drop(accumulator, drop_lowest, false);
                WeightedValue.drop(accumulator, drop_highest, true);
            }
        }
        
        model.add(new Pair<Long, Double>(model_ts.toEpochSecond(),
                WeightedValue.aggregate(accumulator, windowAggregator)));

        model_ts = model_ts.plus(interval, intervalUnits);
        if (model_ts.toEpochSecond() > end_ts.toEpochSecond()) {
            prediction_index++;
            if (prediction_index >= futureWindows) {
                break;
            }
            model_ts = Instant.ofEpochSecond(modelStartEpoch).atZone(zone);
            model_ts = model_ts.plus(
                    (windowDistanceInterval * prediction_index), 
                    windowDistanceIntervalUnits);
            end_ts = model_ts.plus(windowSize, windowUnits);
            for (int i = 0; i < windowTimes.length; i++) {
                windowTimes[i] = null;
                indices[i] = 0;
            }
            initializeIndices(data, model_ts.toEpochSecond());
        }
    }
}
 
Example 14
Source File: BasicItemProvider.java    From calendar-component with Apache License 2.0 4 votes vote down vote up
@Override
public List<ITEM> getItems(ZonedDateTime startDate, ZonedDateTime endDate) {

    final long startRange = startDate.toEpochSecond();
    final long endRange = endDate.toEpochSecond();

    return itemList.parallelStream().filter(i -> {

        long itemStart = i.getStart().toEpochSecond();
        long itemEnd = i.getEnd().toEpochSecond();

        // Select only items that overlaps with startDate and endDate.

        return ((itemStart >= startRange && itemStart <= endRange)
                || (itemEnd >= startRange && itemEnd <= endRange)
                || (itemStart <= startRange && itemEnd >= endRange));

    }).collect(Collectors.toList());
}
 
Example 15
Source File: VisualGraphOpener.java    From constellation with Apache License 2.0 4 votes vote down vote up
/**
 * Open a graph file into a VisualTopComponent.
 * <p>
 * A check is done to see if the file to be opened is already open. If it
 * is, that TopComponent is made active, rather than opening the file again.
 *
 * @param gdo The GraphDataObject to read from.
 */
@Override
public void openGraph(final GraphDataObject gdo) {
    for (TopComponent tc : TopComponent.getRegistry().getOpened()) {
        if (tc instanceof VisualGraphTopComponent) {
            // Get the VisualTopComponent's GraphDataObject from its Lookup.
            // Two DataObjects are equivalent if their primary files are equal.
            final GraphDataObject existingGdo = tc.getLookup().lookupAll(GraphDataObject.class).iterator().next();
            if (gdo.equals(existingGdo)) {
                tc.requestActive();
                return;
            }
        }
    }

    // The file isn't already open.
    // Check to see if there is a more recent autosave for this file.
    // If there is, ask the user if they want to open it.
    final File f = FileUtil.toFile(gdo.getPrimaryFile());
    final Properties props = AutosaveUtilities.getAutosave(f);
    if (props != null) {
        final String dtprop = props.getProperty(AutosaveUtilities.DT);
        if (dtprop != null) {
            final ZonedDateTimeAttributeDescription datetimeAttributeDescription = new ZonedDateTimeAttributeDescription();
            final ZonedDateTime zdtAutosave = datetimeAttributeDescription.convertFromString(dtprop);
            final long dtFile = f.lastModified();
            if (zdtAutosave.toEpochSecond() * 1000 > dtFile) {
                final String dtf = new Date(dtFile).toString();
                final String msg = Bundle.MSG_Autosave(f.getPath(), dtf, dtprop);
                final NotifyDescriptor nd = new NotifyDescriptor(msg, "Open autosaved file?", NotifyDescriptor.YES_NO_OPTION, NotifyDescriptor.QUESTION_MESSAGE, null, null);
                if (DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.YES_OPTION) {
                    // The user wants the more recent autosaved version.
                    // Rename the actual file (to .bak), copy the autosaved version to the actual name, and delete the bak file.
                    final File autosaved = new File(AutosaveUtilities.getAutosaveDir(), props.getProperty(AutosaveUtilities.ID) + GraphDataObject.FILE_EXTENSION);
                    try {
                        AutosaveUtilities.copyFile(autosaved, f);
                    } catch (IOException ex) {
                        LOGGER.log(Level.WARNING, "Copying autosaved file", ex);
                    }
                }

                AutosaveUtilities.deleteAutosave(props.getProperty(AutosaveUtilities.ID));
            }
        }
    }

    // The file isn't already open, so open it.
    new GraphFileOpener(gdo, null, null).execute();
}
 
Example 16
Source File: PersistenceResource.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
private Response putItemState(@Nullable String serviceId, String itemName, String value, @Nullable String time) {
    // If serviceId is null, then use the default service
    String effectiveServiceId = serviceId != null ? serviceId : persistenceServiceRegistry.getDefaultId();
    PersistenceService service = persistenceServiceRegistry.get(effectiveServiceId);

    if (service == null) {
        logger.warn("Persistence service not found '{}'.", effectiveServiceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST,
                "Persistence service not found: " + effectiveServiceId);
    }

    Item item;
    try {
        item = itemRegistry.getItem(itemName);
    } catch (ItemNotFoundException e) {
        logger.warn("Item not found '{}'.", itemName);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Item not found: " + itemName);
    }

    // Try to parse a State from the input
    State state = TypeParser.parseState(item.getAcceptedDataTypes(), value);
    if (state == null) {
        // State could not be parsed
        logger.warn("Can't persist item {} with invalid state '{}'.", itemName, value);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "State could not be parsed: " + value);
    }

    ZonedDateTime dateTime = null;
    if (time != null && time.length() != 0) {
        dateTime = convertTime(time);
    }
    if (dateTime == null || dateTime.toEpochSecond() == 0) {
        logger.warn("Error with persistence store to {}. Time badly formatted {}.", itemName, time);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Time badly formatted.");
    }

    if (!(service instanceof ModifiablePersistenceService)) {
        logger.warn("Persistence service not modifiable '{}'.", effectiveServiceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST,
                "Persistence service not modifiable: " + effectiveServiceId);
    }

    ModifiablePersistenceService mService = (ModifiablePersistenceService) service;

    mService.store(item, Date.from(dateTime.toInstant()), state);
    return Response.status(Status.OK).build();
}
 
Example 17
Source File: QueryUtils.java    From catatumbo with Apache License 2.0 3 votes vote down vote up
/**
 * Converts the given OffsetDateTime to a Timestamp.
 * 
 * @param zonedDateTime
 *          the {@link ZonedDateTime} to convert
 * @return Timestamp object that is equivalent to the given OffsetDateTime.
 */
private static Timestamp toTimestamp(ZonedDateTime zonedDateTime) {
  long seconds = zonedDateTime.toEpochSecond();
  int nanos = zonedDateTime.getNano();
  long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos);
  return Timestamp.ofTimeMicroseconds(microseconds);
}
 
Example 18
Source File: ResourceChartController.java    From logbook-kai with MIT License 2 votes vote down vote up
/**
 * 開発資材を取得します。
 * @param from 開始日時
 * @return 開発資材
 */
public XYChart.Data<Number, Number> getResearchSeries(ZonedDateTime from) {
    return new XYChart.Data<>(this.date.toEpochSecond() - from.toEpochSecond(), this.research);
}
 
Example 19
Source File: ResourceChartController.java    From logbook-kai with MIT License 2 votes vote down vote up
/**
 * 改修資材を取得します。
 * @param from 開始日時
 * @return 改修資材
 */
public XYChart.Data<Number, Number> getImproveSeries(ZonedDateTime from) {
    return new XYChart.Data<>(this.date.toEpochSecond() - from.toEpochSecond(), this.improve);
}
 
Example 20
Source File: ResourceChartController.java    From logbook-kai with MIT License 2 votes vote down vote up
/**
 * 燃料を取得します。
 * @param from 開始日時
 * @return 燃料
 */
public XYChart.Data<Number, Number> getFuelSeries(ZonedDateTime from) {
    return new XYChart.Data<>(this.date.toEpochSecond() - from.toEpochSecond(), this.fuel);
}