Example usage for java.time LocalDateTime from

List of usage examples for java.time LocalDateTime from

Introduction

In this page you can find the example usage for java.time LocalDateTime from.

Prototype

public static LocalDateTime from(TemporalAccessor temporal) 

Source Link

Document

Obtains an instance of LocalDateTime from a temporal object.

Usage

From source file:Main.java

public static void main(String[] args) {
    LocalDateTime a = LocalDateTime.from(ZonedDateTime.now());

    System.out.println(a);
}

From source file:Main.java

public static void main(String[] args) {
    LocalDate february20th = LocalDate.of(2014, Month.FEBRUARY, 20);
    System.out.println(february20th);
    System.out.println(LocalDate.from(february20th.plus(15, ChronoUnit.YEARS))); // 2029-02-20
    System.out.println(LocalDate.MAX);
    System.out.println(LocalDate.MIN);

    System.out.println(LocalTime.MIDNIGHT); // 00:00
    System.out.println(LocalTime.NOON); // 12:00
    System.out.println(LocalTime.of(23, 12, 30, 500)); // 23:12:30.000000500
    System.out.println(LocalTime.now()); // 00:40:34.110
    System.out.println(LocalTime.ofSecondOfDay(11 * 60 * 60)); // 11:00
    System.out.println(LocalTime.from(LocalTime.MIDNIGHT.plusHours(4))); // 04:00
    System.out.println(LocalTime.MIN);
    System.out.println(LocalTime.MAX);

    System.out.println(LocalDateTime.of(2014, 2, 15, 12, 30, 50, 200)); // 2014-02-15T12:30:50.000000200
    System.out.println(LocalDateTime.now()); // 2014-02-28T17:28:21.002
    System.out.println(LocalDateTime.from(LocalDateTime.of(2014, 2, 15, 12, 30, 40, 500).plusHours(19))); // 2014-02-16T07:30:40.000000500
    System.out.println(LocalDateTime.MAX);
}

From source file:Main.java

public static void parseStr(DateTimeFormatter formatter, String text) {
    try {// w ww . ja  v  a  2  s. c  o m
        TemporalAccessor ta = formatter.parseBest(text, OffsetDateTime::from, LocalDateTime::from,
                LocalDate::from);
        if (ta instanceof OffsetDateTime) {
            OffsetDateTime odt = OffsetDateTime.from(ta);
            System.out.println("OffsetDateTime: " + odt);
        } else if (ta instanceof LocalDateTime) {
            LocalDateTime ldt = LocalDateTime.from(ta);
            System.out.println("LocalDateTime: " + ldt);
        } else if (ta instanceof LocalDate) {
            LocalDate ld = LocalDate.from(ta);
            System.out.println("LocalDate: " + ld);
        } else {
            System.out.println("Parsing returned: " + ta);
        }
    } catch (DateTimeParseException e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.orange.clara.tool.schedulers.SchedulerWatchedResources.java

@Scheduled(fixedDelay = 5000)
public void refreshResource() throws AsyncTaskException {
    logger.debug("Running: refresh watched resource scheduled task ...");
    Iterable<WatchedResource> watchedResources = this.watchedResourceRepo.findAll();
    LocalDateTime whenRemoveDateTime;
    for (WatchedResource watchedResource : watchedResources) {
        if (watchedResource.getUpdatedResourceAt() == null) {
            continue;
        }//from  ww w  . ja  va 2  s  . co m
        whenRemoveDateTime = LocalDateTime
                .from(watchedResource.getUpdatedResourceAt().toInstant().atZone(ZoneId.systemDefault()))
                .plusMinutes(updateAfterMinutes);
        if (LocalDateTime.from(Calendar.getInstance().toInstant().atZone(ZoneId.systemDefault()))
                .isBefore(whenRemoveDateTime) || watchedResource.isLocked()) {
            continue;
        }
        watchedResource.setLocked(true);
        this.watchedResourceRepo.save(watchedResource);
        this.refreshTask.runTask(watchedResource.getId());
    }
    logger.debug("Finished: refresh watched resource scheduled task.");
}

From source file:com.orange.clara.cloud.servicedbdumper.task.ScheduledDeleteAllDumpsTask.java

@Scheduled(fixedDelay = 7000)
public void deleteAllDumps() throws JobCreationException, AsyncTaskException {
    List<Job> jobs = jobRepo.findByJobTypeAndJobEvent(JobType.DELETE_DUMPS, JobEvent.START);
    logger.debug("Running: delete all dump scheduled task ...");

    LocalDateTime whenRemoveDateTime;
    for (Job job : jobs) {
        whenRemoveDateTime = LocalDateTime.from(job.getUpdatedAt().toInstant().atZone(ZoneId.systemDefault()))
                .plusDays(this.dumpDeleteExpirationDays);
        if (LocalDateTime.from(Calendar.getInstance().toInstant().atZone(ZoneId.systemDefault()))
                .isBefore(whenRemoveDateTime)) {
            continue;
        }/*  w  w  w.j  a  v  a 2s. c  om*/
        job.setJobEvent(JobEvent.RUNNING);
        jobRepo.save(job);
        this.deleteDumpTask.runTask(job.getId());
    }

    logger.debug("Finished: delete all dump scheduled task.");
}

From source file:com.orange.clara.cloud.servicedbdumper.task.ScheduledManagingJobTask.java

@Scheduled(fixedDelay = 1200000)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void cleaningDeletedDumpFile() {
    logger.debug("Running: cleaning deleted dump task ...");
    List<DatabaseDumpFile> databaseDumpFiles = this.databaseDumpFileRepo.findByDeletedTrueOrderByDeletedAtAsc();
    LocalDateTime whenRemoveDateTime;
    for (DatabaseDumpFile databaseDumpFile : databaseDumpFiles) {
        whenRemoveDateTime = LocalDateTime
                .from(databaseDumpFile.getDeletedAt().toInstant().atZone(ZoneId.systemDefault()))
                .plusDays(this.dumpDeleteExpirationDays);
        if (LocalDateTime.from(Calendar.getInstance().toInstant().atZone(ZoneId.systemDefault()))
                .isBefore(whenRemoveDateTime)) {
            continue;
        }//from  w ww.  j  a  va2s  .  c om
        this.deleter.delete(databaseDumpFile);
    }
    logger.debug("Finished: cleaning deleted dump task.");
}

From source file:be.wegenenverkeer.common.resteasy.json.Iso8601AndOthersLocalDateTimeFormat.java

/**
 * Parse string to date./*w  w  w  .j a  v  a2s.  c  o  m*/
 *
 * @param str string to parse
 * @return date
 */
public LocalDateTime parse(String str) {
    LocalDateTime date = null;

    if (StringUtils.isNotBlank(str)) {
        // try full ISO 8601 format first
        try {
            Date timestamp = ISO8601Utils.parse(str, new ParsePosition(0));
            Instant instant = Instant.ofEpochMilli(timestamp.getTime());
            return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        } catch (IllegalArgumentException | ParseException ex) {
            // ignore, try next format
            date = null; // dummy
        }
        // then try ISO 8601 format without timezone
        try {
            return LocalDateTime.from(iso8601NozoneFormat.parse(str));
        } catch (IllegalArgumentException | DateTimeParseException ex) {
            // ignore, try next format
            date = null; // dummy
        }

        // then try a list of formats
        for (DateTimeFormatter formatter : FORMATS) {
            try {
                TemporalAccessor ta = formatter.parse(str);
                try {
                    return LocalDateTime.from(ta);
                } catch (DateTimeException dte) {
                    return LocalDate.from(ta).atStartOfDay();
                }
            } catch (IllegalArgumentException | DateTimeParseException e) {
                // ignore, try next format
                date = null; // dummy
            }
        }
        throw new IllegalArgumentException("Could not parse date " + str
                + " using ISO 8601 or any of the formats " + Arrays.asList(FORMATS) + ".");

    }
    return date; // empty string
}

From source file:com.buffalokiwi.api.APIDate.java

/**
 * Attempt to take some value and turn it into a valid APIDate.
 * If it isn't valid, then this returns null.
 * // ww w  .  j a va  2 s. com
 * @param value Jet value 
 * @return date or null
 */
public static APIDate fromStringOrNull(String value) {
    if (value == null || value.isEmpty())
        return null;

    for (final DateTimeFormatter fmt : FORMATS) {
        try {
            final TemporalAccessor t = fmt.parse(value);

            try {
                return new APIDate(ZonedDateTime.from(t));
            } catch (DateTimeException e) {
                APILog.warn(LOG, e, "Failed to determine timezone.  Defaulting to local offset");
                final LocalDateTime local = LocalDateTime.from(t);
                final ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
                return new APIDate(ZonedDateTime.of(local, offset));
            }
        } catch (DateTimeParseException e) {
            //..do nothing, yet.
        }
    }

    //..Not found.  Log it and return null
    APILog.error(LOG, "Failed to parse date string:", value);
    return null;
}

From source file:alfio.controller.api.AttendeeApiController.java

@RequestMapping(value = "/{eventKey}/sponsor-scan/mine", method = RequestMethod.GET)
public ResponseEntity<List<SponsorAttendeeData>> getScannedBadges(
        @PathVariable("eventKey") String eventShortName,
        @RequestParam(value = "from", required = false) String from, Principal principal) {

    ZonedDateTime start = Optional.ofNullable(StringUtils.trimToNull(from))
            .map(EventUtil.JSON_DATETIME_FORMATTER::parse)
            .flatMap(d -> Wrappers.safeSupplier(() -> ZonedDateTime.of(LocalDateTime.from(d), ZoneOffset.UTC)))
            .orElse(SponsorScanRepository.DEFAULT_TIMESTAMP);
    return attendeeManager.retrieveScannedAttendees(eventShortName, principal.getName(), start)
            .map(ResponseEntity::ok).orElse(notFound());
}

From source file:org.thevortex.lighting.jinks.robot.Recurrence.java

/**
 * Get the next occurrence from a time.// w w w .  j  ava  2s .co  m
 *
 * @param fromWhen when
 * @return the next occurrence or {@code null} if there is no more
 */
public LocalDateTime nextOccurrence(TemporalAccessor fromWhen) {
    LocalDateTime from = LocalDateTime.from(fromWhen);

    // if it's not today, try the next day
    if (frequency == Frequency.WEEKLY && !days.contains(from.getDayOfWeek())) {
        return nextOccurrence(from.plusDays(1).truncatedTo(ChronoUnit.DAYS));
    }

    // if we've already started, it's too late - next day
    if (from.toLocalTime().isAfter(startTime)) {
        return nextOccurrence(from.plusDays(1).truncatedTo(ChronoUnit.DAYS));
    }

    // otherwise, we're on the right day, so just adjust the time
    return from.with(startTime).truncatedTo(ChronoUnit.MINUTES);
}