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

The following examples show how to use java.time.LocalDateTime#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: StaticFileServerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private Long writeModificationTime() throws MalformedURLException {
    LocalDateTime modificationTime = LocalDateTime.of(2016, 2, 2, 0, 0, 0);
    Long modificationTimestamp = modificationTime
            .toEpochSecond(ZoneOffset.UTC) * 1000;
    String filename = "modified-1d-ago.txt";
    URL resourceUrl = new URL("file", "", -1, filename,
            new URLStreamHandler() {
                @Override
                protected URLConnection openConnection(URL u)
                        throws IOException {
                    URLConnection mock = Mockito.mock(URLConnection.class);
                    Mockito.when(mock.getLastModified())
                            .thenReturn(modificationTimestamp);
                    return mock;
                }
            });

    fileServer.writeModificationTimestamp(resourceUrl, request, response);
    return modificationTimestamp;
}
 
Example 3
Source File: CronType.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private long prevTime(int year, int month, int day, int hour, int minute)
{
  LocalDateTime time = LocalDateTime.of(year, month, day, hour, minute);
  
  /*
  Instant instant = Instant.QDate cal = allocateCalendar();
  
  cal.setLocalTime(0);

  cal.setYear(year);
  cal.setMonth(month);
  cal.setDayOfMonth(day);
  cal.setHour(hour);
  cal.setMinute(minute);

  long time = cal.getGMTTime();

  freeCalendar(cal);
  */

  return time.toEpochSecond(ZoneOffset.UTC);
}
 
Example 4
Source File: CronType.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private long nextTime(int year, int month, int day, int hour, int minute)
{
  LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute);
  /*
  //QDate cal = allocateCalendar();

  cal.setLocalTime(0);

  cal.setYear(year);
  cal.setMonth(month);
  cal.setDayOfMonth(day);
  cal.setHour(hour);
  cal.setMinute(minute);

  long time = cal.getGMTTime();

  freeCalendar(cal);
  */

  return dateTime.toEpochSecond(ZoneOffset.UTC) * 1000;
}
 
Example 5
Source File: TimeSequenceParser.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parses duration string
 *
 * @param value String to parse
 * @return Amount of duration in milliseconds
 */
public static long parseShort(@NonNull String value) {
    Matcher matcher = SHORT_SEQ_PATTERN.matcher(value.toLowerCase()); // for some reason case-insensitive regex is not working for Cyrillic
    if (!matcher.matches()) {
        throw new IllegalArgumentException("Incorrect period/duration: " + value);
    }
    LocalDateTime offsetDateTime = LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC);
    offsetDateTime = addUnit(offsetDateTime, ChronoUnit.YEARS, matcher.group(2));
    offsetDateTime = addUnit(offsetDateTime, ChronoUnit.MONTHS, matcher.group(5));
    offsetDateTime = addUnit(offsetDateTime, ChronoUnit.WEEKS, matcher.group(8));
    offsetDateTime = addUnit(offsetDateTime, ChronoUnit.DAYS, matcher.group(11));
    offsetDateTime = addUnit(offsetDateTime, ChronoUnit.HOURS, matcher.group(14));
    offsetDateTime = addUnit(offsetDateTime, ChronoUnit.MINUTES, matcher.group(17));
    offsetDateTime = addUnit(offsetDateTime, ChronoUnit.SECONDS, matcher.group(20));
    return offsetDateTime.toEpochSecond(ZoneOffset.UTC) * 1000;
}
 
Example 6
Source File: RTC.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
public long getTime() {
    ZoneId zone;
    if (tzName != null) {
        zone = tzName;
    } else {
        zone = DateTimeUtils.UTC;
    }

    LocalDateTime ldt = LocalDateTime.now(zone);
    return ldt.toEpochSecond(ZoneOffset.UTC);
}
 
Example 7
Source File: DateTimeColumn.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the seconds from epoch for each value as an array based on the given offset
 *
 * <p>If a value is missing, DateTimeColumnType.missingValueIndicator() is used
 */
public long[] asEpochSecondArray(ZoneOffset offset) {
  long[] output = new long[data.size()];
  for (int i = 0; i < data.size(); i++) {
    LocalDateTime dateTime = PackedLocalDateTime.asLocalDateTime(data.getLong(i));
    if (dateTime == null) {
      output[i] = DateTimeColumnType.missingValueIndicator();
    } else {
      output[i] = dateTime.toEpochSecond(offset);
    }
  }
  return output;
}
 
Example 8
Source File: ExprDateParsed.java    From skUtilities with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Nullable
protected Date[] get(Event e) {
  String s = id.getSingle(e);
  try {
    String ddf = new SimpleDateFormat().toPattern();
    if (format != null) ddf = format.getSingle(e);
    LocalDateTime ldt = LocalDateTime.parse(s, DateTimeFormatter.ofPattern(ddf));
    return new Date[]{new Date((ldt.toEpochSecond(ZoneOffset.ofTotalSeconds(ldt.getSecond())) + ldt.getSecond()) * 1000)};
  } catch (Exception x) {
    skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 9
Source File: DateTimeColumn.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the seconds from epoch for each value as an array based on the given offset
 *
 * <p>If a value is missing, DateTimeColumnType.missingValueIndicator() is used
 */
public long[] asEpochSecondArray(ZoneOffset offset) {
  long[] output = new long[data.size()];
  for (int i = 0; i < data.size(); i++) {
    LocalDateTime dateTime = PackedLocalDateTime.asLocalDateTime(data.getLong(i));
    if (dateTime == null) {
      output[i] = DateTimeColumnType.missingValueIndicator();
    } else {
      output[i] = dateTime.toEpochSecond(offset);
    }
  }
  return output;
}
 
Example 10
Source File: Core.java    From DataDefender with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a random date-time between the passed start and end dates, and
 * using the passed format to parse the dates passed, and to format the
 * return value.
 *
 * @param start
 * @param end
 * @param format
 * @return
 */
public String randomDateTime(
    @NamedParameter("start") String start,
    @NamedParameter("end") String end,
    @NamedParameter("format") String format
) {
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern(format);
    LocalDateTime ds = LocalDateTime.parse(start, fmt);
    LocalDateTime de = LocalDateTime.parse(end, fmt);
    long day = RandomUtils.nextLong(0, de.toEpochSecond(ZoneOffset.UTC) - ds.toEpochSecond(ZoneOffset.UTC)) + ds.toEpochSecond(ZoneOffset.UTC);
    return LocalDateTime.ofEpochSecond(day, 0, ZoneOffset.UTC).format(fmt);
}
 
Example 11
Source File: SeedWordsView.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void doRestore() {
    LocalDate walletDate = getWalletDate();
    // We subtract 1 day to be sure to not have any issues with timezones. Even if we can be sure that the timezone
    // is handled correctly it could be that the user created the wallet in one timezone and make a restore at
    // a different timezone which could lead in the worst case that he miss the first day of the wallet transactions.
    LocalDateTime localDateTime = walletDate.atStartOfDay().minusDays(1);
    long date = localDateTime.toEpochSecond(ZoneOffset.UTC);

    DeterministicSeed seed = new DeterministicSeed(Splitter.on(" ").splitToList(seedWordsTextArea.getText()), null, "", date);
    GUIUtil.restoreSeedWords(seed, walletsManager, storageDir);
}
 
Example 12
Source File: TYChartItem.java    From charts with Apache License 2.0 4 votes vote down vote up
public TYChartItem(final LocalDateTime T, final double Y, final String NAME, final Color FILL, final Symbol SYMBOL) {
    super(T.toEpochSecond(Helper.getZoneOffset()), Y, NAME, FILL, Color.TRANSPARENT, SYMBOL);
    _t = T;
}
 
Example 13
Source File: Axis.java    From charts with Apache License 2.0 4 votes vote down vote up
private List<LocalDateTime> createTickValues(final double WIDTH, final LocalDateTime START, final LocalDateTime END) {
    List<LocalDateTime> dateList = new ArrayList<>();
    LocalDateTime       dateTime = LocalDateTime.now();

    if (null == START || null == END) return dateList;

    // The preferred gap which should be between two tick marks.
    double majorTickSpace = 100;
    double noOfTicks      = WIDTH / majorTickSpace;

    List<LocalDateTime> previousDateList = new ArrayList<>();
    Interval            previousInterval = Interval.values()[0];

    // Starting with the greatest interval, add one of each dateTime unit.
    for (Interval interval : Interval.values()) {
        // Reset the dateTime.
        dateTime = LocalDateTime.of(START.toLocalDate(), START.toLocalTime());
        // Clear the list.
        dateList.clear();
        previousDateList.clear();
        currentInterval = interval;

        // Loop as long we exceeded the END bound.
        while(dateTime.isBefore(END)) {
            dateList.add(dateTime);
            dateTime = dateTime.plus(interval.getAmount(), interval.getInterval());
        }

        // Then check the size of the list. If it is greater than the amount of ticks, take that list.
        if (dateList.size() > noOfTicks) {
            dateTime = LocalDateTime.of(START.toLocalDate(), START.toLocalTime());
            // Recheck if the previous interval is better suited.
            while(dateTime.isBefore(END) || dateTime.isEqual(END)) {
                previousDateList.add(dateTime);
                dateTime = dateTime.plus(previousInterval.getAmount(), previousInterval.getInterval());
            }
            break;
        }

        previousInterval = interval;
    }
    if (previousDateList.size() - noOfTicks > noOfTicks - dateList.size()) {
        dateList = previousDateList;
        currentInterval = previousInterval;
    }

    // At last add the END bound.
    dateList.add(END);

    List<LocalDateTime> evenDateList = makeDatesEven(dateList, dateTime);
    // If there are at least three dates, check if the gap between the START date and the second date is at least half the gap of the second and third date.
    // Do the same for the END bound.
    // If gaps between dates are to small, remove one of them.
    // This can occur, e.g. if the START bound is 25.12.2013 and years are shown. Then the next year shown would be 2014 (01.01.2014) which would be too narrow to 25.12.2013.
    if (evenDateList.size() > 2) {
        LocalDateTime secondDate       = evenDateList.get(1);
        LocalDateTime thirdDate        = evenDateList.get(2);
        LocalDateTime lastDate         = evenDateList.get(dateList.size() - 2);
        LocalDateTime previousLastDate = evenDateList.get(dateList.size() - 3);

        // If the second date is too near by the START bound, remove it.
        if (secondDate.toEpochSecond(ZoneOffset.ofHours(0)) - START.toEpochSecond(ZoneOffset.ofHours(0)) < thirdDate.toEpochSecond(ZoneOffset.ofHours(0)) - secondDate.toEpochSecond(ZoneOffset.ofHours(0))) {
            evenDateList.remove(secondDate);
        }

        // If difference from the END bound to the last date is less than the half of the difference of the previous two dates,
        // we better remove the last date, as it comes to close to the END bound.
        if (END.toEpochSecond(ZoneOffset.ofHours(0)) - lastDate.toEpochSecond(ZoneOffset.ofHours(0)) < ((lastDate.toEpochSecond(ZoneOffset.ofHours(0)) - previousLastDate.toEpochSecond(ZoneOffset.ofHours(0)) * 0.5))) {
            evenDateList.remove(lastDate);
        }
    }
    return evenDateList;
}
 
Example 14
Source File: EventController.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
@ApiOperation("Count of elements in specified events source since specified time (24 hours by default)." +
  " Note that not all sources have persisted store, these sources do not support getting count.")
@RequestMapping(value = "/{source:.*}/count", method = RequestMethod.GET)
public UiCountResult countOfLastEvents(@PathVariable("source") String source,
                                       @RequestParam(name = "filter", required = false) List<String> filtersSrc,
                                       @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
                                       @RequestParam(name = "from", required = false) LocalDateTime from) {
    Subscriptions<?> subs = sources.get(source);
    ExtendedAssert.notFound(subs, "Can not find Subscriptions: '" + source + "'");
    PersistentBusFactory.PersistentBus<?> pb = subs.getExtension(PersistentBusFactory.EXT_KEY);
    ExtendedAssert.notFound(pb, "Can not find persisted queue: '" + source + "'");
    List<FilterCollector> collectors = new ArrayList<>();
    if(filtersSrc != null) {
        filtersSrc.forEach((src) -> collectors.add(new FilterCollector(filterFactory, src)));
    }
    if(from == null) {
        from = LocalDateTime.now().minusDays(1);
    }
    long fromMillis = from.toEpochSecond(ZoneOffset.UTC);
    FbQueue<?> q = pb.getQueue();
    Iterator<?> iter = q.iterator();
    int i = 0;
    while(iter.hasNext()) {
        Object next = iter.next();
        if(!(next instanceof EventWithTime)) {
            continue;
        }
        long millis = ((EventWithTime) next).getTimeInMilliseconds();
        if(millis < fromMillis) {
            continue;
        }
        collectors.forEach(fc -> fc.collect(next));
        i++;
    }
    UiCountResult res = new UiCountResult();
    res.setFiltered(collectors.stream().map(FilterCollector::toUi).collect(Collectors.toList()));
    res.setSource(source);
    res.setCount(i);
    res.setFrom(from);
    return res;
}
 
Example 15
Source File: EpochTimestamps.java    From roboslack with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unused") // Called via reflection
private static long convertLocalDateTime(LocalDateTime localDateTime) {
    return localDateTime.toEpochSecond(UTC_OFFSET);
}
 
Example 16
Source File: OracleConnectorIT.java    From debezium-incubator with Apache License 2.0 4 votes vote down vote up
private long toMicroSecondsSinceEpoch(LocalDateTime localDateTime) {
    return localDateTime.toEpochSecond(ZoneOffset.UTC) * MICROS_PER_SECOND;
}
 
Example 17
Source File: ExprDateInner.java    From skUtilities with GNU General Public License v3.0 4 votes vote down vote up
@Override
@Nullable
protected String[] get(Event e) {
  Date d = new Date(id.getSingle(e).getTimestamp() * 1000L);
  try {
    LocalDateTime ldt = LocalDateTime.parse(d.toString(), DateTimeFormatter.ofPattern(new SimpleDateFormat().toPattern()));
    switch (ty) {
      case 0: {
        return new String[]{String.valueOf(ldt.getYear())};
      } case 1: {
        return new String[]{String.valueOf(ldt.getMonthValue())};
      } case 2: {
        return new String[]{ldt.getMonth().name()};
      } case 3: {
        return new String[]{String.valueOf(ldt.getDayOfYear())};
      } case 4: {
        return new String[]{String.valueOf(ldt.getDayOfMonth())};
      } case 5: {
        return new String[]{String.valueOf(ldt.getDayOfWeek().getValue())};
      } case 6: {
        return new String[]{ldt.getDayOfWeek().name()};
      } case 7: {
        return new String[]{String.valueOf(ldt.getHour())};
      } case 8: {
        return new String[]{String.valueOf(ldt.getMinute())};
      } case 9: {
        long ul = (id.getSingle(e).getTimestamp() / 1000L) - (ldt.toEpochSecond(ZoneOffset.ofTotalSeconds(ldt.getSecond())));
        while (ul > 59) {
          if (ul > 3600) {
            ul = (ul - 3600);
          } else {
            ul = (ul - 900);
          }
        }
        return new String[]{String.valueOf(ul)};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 18
Source File: AmodeusTimeConvert.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
public long toEpochSec(LocalDateTime localDateTime) {
    return localDateTime.toEpochSecond(localDateTime.atZone(zoneId).getOffset());
}
 
Example 19
Source File: ReportingModelTest.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testEmailDynamicPart() {
    ReportDataStream reportDataStream = new ReportDataStream((short) 1, PinType.VIRTUAL, "Temperature", true);

    ReportSource reportSource2 = new TileTemplateReportSource(
            new ReportDataStream[] {reportDataStream},
            1,
            new int[] {0, 1}
    );

    Report report = new Report(1, "My One Time Report",
            new ReportSource[] {reportSource2},
            new OneTimeReport(86400), "[email protected]",
            GraphGranularityType.MINUTE, true, CSV_FILE_PER_DEVICE_PER_PIN, null, ZoneId.of("UTC"), 0, 0, null);

    LocalDateTime localDateTime = LocalDateTime.of(2018, 2, 20, 10, 10);
    long millis = localDateTime.toEpochSecond(ZoneOffset.UTC) * 1000;

    Report report2 = new Report(2, "My Daily Report",
            new ReportSource[] {reportSource2},
            new DailyReport(millis, ReportDurationType.CUSTOM, millis, millis), "[email protected]",
            GraphGranularityType.MINUTE, true, CSV_FILE_PER_DEVICE_PER_PIN, null, ZoneId.of("UTC"), 0, 0, null);

    LocalDateTime start = LocalDateTime.of(2018, 3, 21, 0, 0, 0);
    LocalDateTime end = LocalDateTime.of(2019, 3, 21, 0, 0, 0);
    Report report3 = new Report(3, "My Weekly Report",
            new ReportSource[] {reportSource2},
            new WeeklyReport(millis, ReportDurationType.CUSTOM, start.toEpochSecond(ZoneOffset.UTC) * 1000, end.toEpochSecond(ZoneOffset.UTC) * 1000, 1), "[email protected]",
            GraphGranularityType.MINUTE, true, CSV_FILE_PER_DEVICE_PER_PIN, null, ZoneId.of("UTC"), 0, 0, null);

    Report report4 = new Report(4, "My Monthly Report",
            new ReportSource[] {reportSource2},
            new MonthlyReport(millis, ReportDurationType.CUSTOM, start.toEpochSecond(ZoneOffset.UTC) * 1000, end.toEpochSecond(ZoneOffset.UTC) * 1000, DayOfMonth.FIRST), "[email protected]",
            GraphGranularityType.MINUTE, true, CSV_FILE_PER_DEVICE_PER_PIN, null, ZoneId.of("UTC"), 0, 0, null);

    Report report5 = new Report(4, "My Monthly Report 2",
            new ReportSource[] {reportSource2},
            new MonthlyReport(millis, ReportDurationType.CUSTOM, start.toEpochSecond(ZoneOffset.UTC) * 1000, end.toEpochSecond(ZoneOffset.UTC) * 1000, DayOfMonth.LAST), "[email protected]",
            GraphGranularityType.MINUTE, true, CSV_FILE_PER_DEVICE_PER_PIN, null, ZoneId.of("UTC"), 0, 0, null);

    Report report6 = new Report(2, "My Daily Report",
            new ReportSource[] {reportSource2},
            new DailyReport(millis, ReportDurationType.INFINITE, millis, millis), "[email protected]",
            GraphGranularityType.MINUTE, true, CSV_FILE_PER_DEVICE_PER_PIN, null, ZoneId.of("UTC"), 0, 0, null);

    assertEquals("Report name: My One Time Report<br>Period: One time", report.buildDynamicSection());
    assertEquals("Report name: My Daily Report<br>Period: Daily, at " + localDateTime.toLocalTime() + "<br>Start date: 2018-02-20<br>End date: 2018-02-20<br>", report2.buildDynamicSection());
    assertEquals("Report name: My Weekly Report<br>Period: Weekly, at " + localDateTime.toLocalTime() + " every Monday<br>Start date: 2018-03-21<br>End date: 2019-03-21<br>", report3.buildDynamicSection());
    assertEquals("Report name: My Monthly Report<br>Period: Monthly, at " + localDateTime.toLocalTime() + " at the first day of every month<br>Start date: 2018-03-21<br>End date: 2019-03-21<br>", report4.buildDynamicSection());
    assertEquals("Report name: My Monthly Report 2<br>Period: Monthly, at " + localDateTime.toLocalTime() + " at the last day of every month<br>Start date: 2018-03-21<br>End date: 2019-03-21<br>", report5.buildDynamicSection());
    assertEquals("Report name: My Daily Report<br>Period: Daily, at " + localDateTime.toLocalTime() + "", report6.buildDynamicSection());
}
 
Example 20
Source File: Helper.java    From charts with Apache License 2.0 votes vote down vote up
public static final long toSeconds(final LocalDateTime DATE_TIME, final ZoneOffset ZONE_OFFSET) { return DATE_TIME.toEpochSecond(ZONE_OFFSET); }