Example usage for java.time LocalDateTime parse

List of usage examples for java.time LocalDateTime parse

Introduction

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

Prototype

public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) 

Source Link

Document

Obtains an instance of LocalDateTime from a text string using a specific formatter.

Usage

From source file:com.btmatthews.atlas.core.dao.mongo.MongoLocalDateTimeDeserializer.java

@Override
public LocalDateTime deserialize(final JsonParser parser, final DeserializationContext context)
        throws IOException {
    final ObjectCodec codec = parser.getCodec();
    final JsonNode node = codec.readTree(parser);
    final JsonNode dateNode = node.get("$date");
    return LocalDateTime.parse(dateNode.asText(), DATE_TIME_FORMATTER);
}

From source file:com.microsoft.sqlserver.testframework.sqlType.SqlDateTime2.java

public Object createdata() {
    Timestamp temp = new Timestamp(ThreadLocalRandom.current().nextLong(((Timestamp) minvalue).getTime(),
            ((Timestamp) maxvalue).getTime()));
    temp.setNanos(0);//www.  j  a v a  2  s  .c om
    String timeNano = temp.toString().substring(0, temp.toString().length() - 1)
            + RandomStringUtils.randomNumeric(this.precision);
    // can pass string rather than converting to LocalDateTime, but leaving
    // it unchanged for now to handle prepared statements
    return LocalDateTime.parse(timeNano, formatter);
}

From source file:eu.hansolo.tilesfx.weather.Sun.java

private static ZonedDateTime[] parseJsonData(final String JSON_DATA, final ZoneId ZONE_ID) {
    Object obj = JSONValue.parse(JSON_DATA);
    JSONObject jsonObj = (JSONObject) obj;

    // Results//from   w  w  w .  ja  v  a  2  s  . c  om
    JSONObject results = (JSONObject) jsonObj.get("results");

    LocalDateTime sunrise = LocalDateTime.parse(results.get("sunrise").toString(),
            DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime sunset = LocalDateTime.parse(results.get("sunset").toString(),
            DateTimeFormatter.ISO_DATE_TIME);
    /*
    LocalDateTime solarNoon                 = LocalDateTime.parse(results.get("solar_noon").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime dayLength                 = LocalDateTime.parse(results.get("day_length").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime civilTwilightBegin        = LocalDateTime.parse(results.get("civil_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime nauticalTwilightBegin     = LocalDateTime.parse(results.get("nautical_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime nauticalTwilightEnd       = LocalDateTime.parse(results.get("nautical_twilight_end").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime astronomicalTwilightBegin = LocalDateTime.parse(results.get("astronomical_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime astronomicalTwilightEnd   = LocalDateTime.parse(results.get("astronomical_twilight_end").toString(), DateTimeFormatter.ISO_DATE_TIME);
    */

    return new ZonedDateTime[] { ZonedDateTime.of(sunrise, ZONE_ID), ZonedDateTime.of(sunset, ZONE_ID) };
}

From source file:net.tradelib.core.Series.java

static public Series fromCsv(String path, boolean header, DateTimeFormatter dtf, LocalTime lt)
        throws Exception {

    if (dtf == null) {
        if (lt == null)
            dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        else//from w  w w  . ja v  a  2  s .  com
            dtf = DateTimeFormatter.ISO_DATE;
    }

    // Parse and import the csv
    CSVFormat csvFmt = CSVFormat.DEFAULT.withCommentMarker('#').withIgnoreSurroundingSpaces();
    if (header)
        csvFmt = csvFmt.withHeader();
    CSVParser csv = csvFmt.parse(new BufferedReader(new FileReader(path)));

    int ncols = -1;
    Series result = null;
    double[] values = null;

    for (CSVRecord rec : csv.getRecords()) {
        if (result == null) {
            ncols = rec.size() - 1;
            values = new double[ncols];
            result = new Series(ncols);
        }

        for (int ii = 0; ii < ncols; ++ii) {
            values[ii] = Double.parseDouble(rec.get(ii + 1));
        }

        LocalDateTime ldt;
        if (lt != null) {
            ldt = LocalDate.parse(rec.get(0), dtf).atTime(lt);
        } else {
            ldt = LocalDateTime.parse(rec.get(0), dtf);
        }

        result.append(ldt, values);
    }

    if (header) {
        Map<String, Integer> headerMap = csv.getHeaderMap();
        result.clearNames();
        for (Map.Entry<String, Integer> me : headerMap.entrySet()) {
            if (me.getValue() > 0)
                result.setName(me.getKey(), me.getValue() - 1);
        }
    }

    return result;
}

From source file:org.jspare.server.transaction.TidGeneratorImpl.java

@Override
public boolean validate(final String tid) {

    try {//from w w w.j  a v  a 2s  .c o  m
        if (StringUtils.isEmpty(tid)) {
            return false;
        }

        String prefix = tid.substring(0, TIMESTAMP_FORMAT.length() + MILLI_OF_SECOND);
        if (!LocalDateTime.parse(prefix, dtf).isBefore(LocalDateTime.now())) {
            return false;
        }

        long sufix = Long
                .parseLong(tid.substring(TIMESTAMP_FORMAT.length() + MILLI_OF_SECOND, tid.length() - 1));
        if (sufix <= MIN || sufix >= MAX) {
            return false;
        }
        int verifyDigit = Integer.parseInt(String.valueOf(tid.charAt(tid.length() - 1)));

        return validateVerifyDigit(tid, verifyDigit);

    } catch (Exception e) {

        return false;
    }
}

From source file:org.codelibs.fess.service.ClickLogService.java

public void importCsv(final Reader reader) {
    final CsvReader csvReader = new CsvReader(reader, new CsvConfig());
    final DateTimeFormatter formatter = DateTimeFormatter
            .ofPattern(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND);
    try {/*from  ww  w  . jav a  2  s .c o  m*/
        List<String> list;
        csvReader.readValues(); // ignore header
        while ((list = csvReader.readValues()) != null) {
            try {
                final String dateStr = list.get(3);
                final String userSessionId = list.get(4);
                final SearchLog searchLog = searchLogBhv.selectEntity(cb -> {
                    cb.query().setRequestedTime_Equal(LocalDateTime.parse(dateStr, formatter));
                    cb.query().setUserSessionId_Equal(userSessionId);
                }).orElse(null);//TODO
                if (searchLog != null) {
                    final ClickLog entity = new ClickLog();
                    entity.setId(Long.parseLong(list.get(0)));
                    entity.setSearchId(searchLog.getId());
                    entity.setUrl(list.get(1));
                    entity.setRequestedTime(LocalDateTime.parse(list.get(2), formatter));
                    clickLogBhv.insert(entity);
                } else {
                    log.warn("The search log is not found: " + list);
                }
            } catch (final Exception e) {
                log.warn("Failed to read a click log: " + list, e);
            }
        }
    } catch (final IOException e) {
        log.warn("Failed to read a click log.", e);
    }
}

From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java

@Override
public Configuration deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

    if (logger.isDebugEnabled()) {
        logger.debug("[DESERIALIZE]");
    }//from  w w w .j  a  v  a 2 s.c o m

    JsonObject obj = (JsonObject) jsonElement;

    JsonElement apElement = obj.get("activeProfile");
    String ap = "";
    if (apElement != null) {
        ap = apElement.getAsString();
    }

    JsonElement jdkElem = obj.get("jdkHome");
    String jdkHome = "";
    if (jdkElem != null) {
        jdkHome = jdkElem.getAsString();
    }

    JsonElement hpElem = obj.get("hashedPassword");
    String hp = "";
    if (hpElem != null) {
        hp = hpElem.getAsString();
    }

    JsonElement ludElem = obj.get("lastUpdatedDate");
    String lud = "";
    LocalDateTime lastUpdatedDate = null;
    if (ludElem != null) {
        lud = ludElem.getAsString();
        if (StringUtils.isNotEmpty(lud)) {
            lastUpdatedDate = LocalDateTime.parse(lud, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }
    }

    JsonArray recentProfiles = obj.getAsJsonArray("recentProfiles");
    JsonArray profiles = obj.getAsJsonArray("profiles");

    if (logger.isDebugEnabled()) {
        logger.debug("[DESERIALIZE] rp={}, ap={}, jdkHome={}, keytool={}, profiles={}",
                recentProfiles.toString(), ap, jdkHome, profiles.toString());
    }

    Configuration conf = new Configuration();
    conf.setActiveProfile(Optional.of(ap));
    conf.setJDKHome(Optional.of(jdkHome));
    conf.getRecentProfiles().addAll(deserializeRecentProfiles(recentProfiles));
    conf.getProfiles().addAll(deserializeProfiles(profiles));
    conf.setHashedPassword(Optional.of(hp));
    conf.setLastUpdatedDateTime(Optional.ofNullable(lastUpdatedDate));
    return conf;
}

From source file:scouterx.webapp.request.SummaryRequest.java

private void setTimeAsYmd() {
    ZoneId zoneId = ZoneId.systemDefault();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
    LocalDateTime startDateTime = LocalDateTime.parse(startYmdHm, formatter);
    LocalDateTime endDateTime = LocalDateTime.parse(endYmdHm, formatter);

    startTimeMillis = startDateTime.atZone(zoneId).toEpochSecond() * 1000L;
    endTimeMillis = endDateTime.atZone(zoneId).toEpochSecond() * 1000L;
}

From source file:de.steilerdev.myVerein.server.controller.user.EventController.java

/**
 * This function gathers all events for the currently logged in user. If lastChanged is stated only events that
 * changed after that moment are returned.
 *
 * @param lastChanged The date of the last changed action, correctly formatted (YYYY-MM-DDTHH:mm:ss)
 * @param currentUser The currently logged in user
 * @return A list of all events for the user that changed since the last changed moment in time (only containing
 * id's)// w ww .ja  v a  2 s  .co m
 */
@RequestMapping(produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<List<Event>> getAllEventsForUser(@RequestParam(required = false) String lastChanged,
        @CurrentUser User currentUser) {
    List<Event> events;
    if (lastChanged != null && !lastChanged.isEmpty()) {
        logger.debug("[{}] Gathering all user events changed after {}", currentUser, lastChanged);
        LocalDateTime lastChangedTime;
        try {
            lastChangedTime = LocalDateTime.parse(lastChanged, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        } catch (DateTimeParseException e) {
            logger.warn("[{}] Unable to get all events for user, because the last changed format is wrong: {}",
                    currentUser, e.getLocalizedMessage());
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        events = eventRepository.findAllByPrefixedInvitedUserAndLastChangedAfter(
                Event.prefixedUserIDForUser(currentUser), lastChangedTime);
    } else {
        logger.debug("[{}] Gathering all user events", currentUser);
        events = eventRepository.findAllByPrefixedInvitedUser(Event.prefixedUserIDForUser(currentUser));
    }

    if (events == null || events.isEmpty()) {
        logger.warn("[{}] No events to return", currentUser);
        return new ResponseEntity<>(HttpStatus.OK);
    } else {
        logger.info("[{}] Returning {} events", currentUser, events.size());
        events.replaceAll(Event::getSendingObjectOnlyId);
        return new ResponseEntity<>(events, HttpStatus.OK);
    }
}

From source file:Main.StaticTools.java

public static ZonedDateTime getTimeFromStr(String input, ZoneId zone) {
    ZonedDateTime result = null;/*from ww  w.j  a  va 2s . c om*/
    try {
        result = LocalDateTime.parse(input, ExifDateFormat).atZone(zone);
    } catch (DateTimeParseException e) {
        try {
            result = LocalDateTime.parse(input, XmpDateFormat).atZone(zone);
        } catch (DateTimeParseException e1) {
        }
    }
    return result;
}