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) 

Source Link

Document

Obtains an instance of LocalDateTime from a text string such as 2007-12-03T10:15:30 .

Usage

From source file:msi.gama.util.GamaDate.java

private static Temporal parse(final IScope scope, final String original, final DateTimeFormatter df) {
    if (original == null || original.isEmpty() || original.equals("now")) {
        return LocalDateTime.now(GamaDateType.DEFAULT_ZONE);
    }//from   w w w.ja va 2 s.  c  om
    Temporal result = null;

    if (df != null) {
        try {
            final TemporalAccessor ta = df.parse(original);
            if (ta instanceof Temporal) {
                return (Temporal) ta;
            }
            if (!ta.isSupported(ChronoField.YEAR) && !ta.isSupported(ChronoField.MONTH_OF_YEAR)
                    && !ta.isSupported(ChronoField.DAY_OF_MONTH)) {
                if (ta.isSupported(ChronoField.HOUR_OF_DAY)) {
                    return LocalTime.from(ta);
                }
            }
            if (!ta.isSupported(ChronoField.HOUR_OF_DAY) && !ta.isSupported(ChronoField.MINUTE_OF_HOUR)
                    && !ta.isSupported(ChronoField.SECOND_OF_MINUTE)) {
                return LocalDate.from(ta);
            }
            return LocalDateTime.from(ta);
        } catch (final DateTimeParseException e) {
            e.printStackTrace();
        }
        GAMA.reportAndThrowIfNeeded(scope,
                GamaRuntimeException.warning(
                        "The date " + original + " can not correctly be parsed by the pattern provided", scope),
                false);
        return parse(scope, original, null);
    }

    String dateStr;
    try {
        // We first make sure all date fields have the correct length and
        // the string is correctly formatted
        String string = original;
        if (!original.contains("T") && original.contains(" ")) {
            string = StringUtils.replaceOnce(original, " ", "T");
        }
        final String[] base = string.split("T");
        final String[] date = base[0].split("-");
        String other;
        if (base.length == 1) {
            other = "00:00:00";
        } else {
            other = base[1];
        }
        String year, month, day;
        if (date.length == 1) {
            // ISO basic date format
            year = date[0].substring(0, 4);
            month = date[0].substring(4, 6);
            day = date[0].substring(6, 8);
        } else {
            year = date[0];
            month = date[1];
            day = date[2];
        }
        if (year.length() == 2) {
            year = "20" + year;
        }
        if (month.length() == 1) {
            month = '0' + month;
        }
        if (day.length() == 1) {
            day = '0' + day;
        }
        dateStr = year + "-" + month + "-" + day + "T" + other;
    } catch (final Exception e1) {
        throw GamaRuntimeException.error("The date " + original
                + " is not correctly formatted. Please refer to the ISO date/time format", scope);
    }

    try {
        result = LocalDateTime.parse(dateStr);
    } catch (final DateTimeParseException e) {
        try {
            result = OffsetDateTime.parse(dateStr);
        } catch (final DateTimeParseException e2) {
            try {
                result = ZonedDateTime.parse(dateStr);
            } catch (final DateTimeParseException e3) {
                throw GamaRuntimeException.error(
                        "The date " + original
                                + " is not correctly formatted. Please refer to the ISO date/time format",
                        scope);
            }
        }
    }

    return result;
}

From source file:svc.managers.SMSManager.java

private String generateViewCitationsAgainMessage(HttpSession session, HttpServletRequest request,
        String menuChoice) {/*  ww w. j ava2 s  . com*/
    String message = "";
    String citationNumber = (String) session.getAttribute("citationNumber");
    String courtDateTime = (String) session.getAttribute("courtDateTime");
    String phoneNumber = (String) session.getAttribute("phoneNumber");
    String dob = (String) session.getAttribute("dob");

    switch (menuChoice) {
    case "1":
        message = generateReadLicenseMessage(session);
        break;
    case "2":
        message = "Visit ";
        message += clientURL + "/citations";
        message += "/" + citationNumber;
        message += replyWithAdditionalViewingOptions();
        setNextStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN);
        break;
    case "3":
        if (smsAlertManager.add(citationNumber, LocalDateTime.parse(courtDateTime), phoneNumber,
                DatabaseUtilities.convertUSStringDateToLD(dob))) {
            //if a demo citation was created automatically send out an sms alert in 1 minute.
            if (citationNumber.startsWith("STLC")) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        smsNotifier.sendAlerts(citationNumber, phoneNumber);
                        smsAlertManager.remove(citationNumber, phoneNumber,
                                DatabaseUtilities.convertUSStringDateToLD(dob));
                    }

                }, 1 * 60 * 1000);
            }

            message = "You will receive 3 text message reminders about your court date.  The first one will be sent two weeks prior to your court date.  The second will be send one week prior and the final one will be sent the day before your court date.";
            message += "\n\n  For help, respond HELP, to stop, respond STOP";
            message += "\n\n Responding with STOP will prevent you from receiving any reminders now and in the future as well as using any part of this SMS service.  If you'd like to cancel your reminder, you can cancel using the same text message menu you used to sign up.";
            message += "\n\n" + replyWithAdditionalViewingOptionsNoText();
            setNextStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN);
        } else {
            message = "Sorry, something went wrong in processing your request for text message reminders.";
            setNextStageInSession(session, SMS_STAGE.WELCOME);
        }
        break;
    case "4":
        if (smsAlertManager.remove(citationNumber, phoneNumber,
                DatabaseUtilities.convertUSStringDateToLD(dob))) {
            message = "You have been removed from receiving text message reminders about this court date.  If there are other court dates you have signed up to receive text message reminders for and you would like to be removed from receiving updates about those dates, please look them up by your citation number and remove them too.";
            message += replyWithAdditionalViewingOptionsNoText();
            setNextStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN);
        } else {
            message = "Sorry, something went wrong in processing your request to be removed from text message reminders.";
            setNextStageInSession(session, SMS_STAGE.WELCOME);
        }
        break;
    default:
        message = "Option not recognized.";
        message += replyWithAdditionalViewingOptions();
        setNextStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN);
        break;
    }

    return message;
}

From source file:net.resheim.eclipse.timekeeper.ui.Activator.java

/**
 * Returns the start time for the task or <code>null</code>.
 *
 * @param task/*ww w. jav a 2 s  . c o m*/
 *            the task to obtain the start time for
 * @return the start time or <code>null</code>
 */
public static LocalDateTime getStartTime(ITask task) {
    String startString = Activator.getValue(task, Activator.START);
    if (startString != null) {
        return LocalDateTime.parse(startString);
    }
    return null;
}

From source file:net.resheim.eclipse.timekeeper.ui.Activator.java

/**
 * Must be called by the UI-thread//from  ww  w . j  av  a 2 s  .  c o m
 *
 * @param idleTimeMillis
 */
private void handleReactivation(long idleTimeMillis) {
    // We want only one dialog open.
    if (dialogIsOpen) {
        return;
    }
    synchronized (this) {
        if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
            // If we have an active task
            ITask task = TasksUi.getTaskActivityManager().getActiveTask();
            if (task != null && Activator.getValue(task, Activator.START) != null) {
                dialogIsOpen = true;
                String tickString = Activator.getValue(task, Activator.TICK);
                LocalDateTime started = getActiveSince();
                LocalDateTime ticked = LocalDateTime.parse(tickString);
                LocalDateTime lastTick = ticked;
                // Subtract the IDLE_INTERVAL time the computer _was_
                // idle while counting up to the threshold. During this
                // period fields were updated. Thus must be adjusted for.
                ticked = ticked.minusNanos(IDLE_INTERVAL);
                String time = DurationFormatUtils.formatDuration(lastIdleTime, "H:mm:ss", true);

                StringBuilder sb = new StringBuilder();
                if (task.getTaskKey() != null) {
                    sb.append(task.getTaskKey());
                    sb.append(": ");
                }
                sb.append(task.getSummary());
                MessageDialog md = new MessageDialog(Display.getCurrent().getActiveShell(),
                        "Disregard idle time?", null,
                        MessageFormat.format(
                                "The computer has been idle since {0}, more than {1}. The active task \"{2}\" was started on {3}. Deactivate the task and disregard the idle time?",
                                ticked.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US)), time,
                                sb.toString(),
                                started.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US))),
                        MessageDialog.QUESTION, new String[] { "No", "Yes" }, 1);
                int open = md.open();
                dialogIsOpen = false;
                if (open == 1) {
                    // Stop task, subtract initial idle time
                    TasksUi.getTaskActivityManager().deactivateTask(task);
                    reduceTime(task, ticked.toLocalDate().toString(), IDLE_INTERVAL / 1000);
                } else {
                    // Continue task, add idle time
                    LocalDateTime now = LocalDateTime.now();
                    long seconds = lastTick.until(now, ChronoUnit.MILLIS);
                    accumulateTime(task, ticked.toLocalDate().toString(), seconds);
                    Activator.setValue(task, Activator.TICK, now.toString());
                }
            }
        }
    }
}

From source file:sx.blah.discord.DiscordClient.java

public LocalDateTime convertFromTimestamp(String time) {
    return LocalDateTime.parse(time.split("\\+")[0]).atZone(ZoneId.of("UTC+00:00"))
            .withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
}

From source file:net.resheim.eclipse.timekeeper.ui.Activator.java

/**
 * Returns the current active time, or <code>null</code> if a task has not
 * been started./*from   ww  w  .ja v  a2  s  .com*/
 *
 * @return the active time or <code>null</code>
 */
public LocalDateTime getActiveSince() {
    ITask task = TasksUi.getTaskActivityManager().getActiveTask();
    if (task != null) {
        String startString = Activator.getValue(task, Activator.START);
        LocalDateTime started = LocalDateTime.parse(startString);
        return started;
    }
    return null;
}

From source file:net.resheim.eclipse.timekeeper.ui.Activator.java

/**
 *
 * @return//from  w  w w  .  ja  v a2 s .  c o  m
 */
public LocalDateTime getIdleSince() {
    ITask task = TasksUi.getTaskActivityManager().getActiveTask();
    if (task != null && Activator.getValue(task, Activator.START) != null) {
        String tickString = Activator.getValue(task, Activator.TICK);
        LocalDateTime ticked = LocalDateTime.parse(tickString);
        ticked = ticked.minusNanos(IDLE_INTERVAL);
        return ticked;
    }
    return null;
}

From source file:org.apache.nifi.processors.solr.SolrUtils.java

private static void writeValue(final SolrInputDocument inputDocument, final Object value,
        final String fieldName, final DataType dataType, final List<String> fieldsToIndex) throws IOException {
    final DataType chosenDataType = dataType.getFieldType() == RecordFieldType.CHOICE
            ? DataTypeUtils.chooseDataType(value, (ChoiceDataType) dataType)
            : dataType;//  w  w w  . j a  v  a  2s  .co  m
    final Object coercedValue = DataTypeUtils.convertType(value, chosenDataType, fieldName);
    if (coercedValue == null) {
        return;
    }

    switch (chosenDataType.getFieldType()) {
    case DATE: {
        final String stringValue = DataTypeUtils.toString(coercedValue,
                () -> DataTypeUtils.getDateFormat(RecordFieldType.DATE.getDefaultFormat()));
        if (DataTypeUtils.isLongTypeCompatible(stringValue)) {
            LocalDate localDate = getLocalDateFromEpochTime(fieldName, coercedValue);
            addFieldToSolrDocument(inputDocument, fieldName,
                    localDate.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z', fieldsToIndex);
        } else {
            addFieldToSolrDocument(inputDocument, fieldName,
                    LocalDate.parse(stringValue).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z',
                    fieldsToIndex);
        }
        break;
    }
    case TIMESTAMP: {
        final String stringValue = DataTypeUtils.toString(coercedValue,
                () -> DataTypeUtils.getDateFormat(RecordFieldType.TIMESTAMP.getDefaultFormat()));
        if (DataTypeUtils.isLongTypeCompatible(stringValue)) {
            LocalDateTime localDateTime = getLocalDateTimeFromEpochTime(fieldName, coercedValue);
            addFieldToSolrDocument(inputDocument, fieldName,
                    localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z', fieldsToIndex);
        } else {
            addFieldToSolrDocument(inputDocument, fieldName,
                    LocalDateTime.parse(stringValue).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z',
                    fieldsToIndex);
        }
        break;
    }
    case DOUBLE:
        addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toDouble(coercedValue, fieldName),
                fieldsToIndex);
        break;
    case FLOAT:
        addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toFloat(coercedValue, fieldName),
                fieldsToIndex);
        break;
    case LONG:
        addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toLong(coercedValue, fieldName),
                fieldsToIndex);
        break;
    case INT:
    case BYTE:
    case SHORT:
        addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toInteger(coercedValue, fieldName),
                fieldsToIndex);
        break;
    case CHAR:
    case STRING:
        addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex);
        break;
    case BIGINT:
        if (coercedValue instanceof Long) {
            addFieldToSolrDocument(inputDocument, fieldName, (Long) coercedValue, fieldsToIndex);
        } else {
            addFieldToSolrDocument(inputDocument, fieldName, (BigInteger) coercedValue, fieldsToIndex);
        }
        break;
    case BOOLEAN:
        final String stringValue = coercedValue.toString();
        if ("true".equalsIgnoreCase(stringValue)) {
            addFieldToSolrDocument(inputDocument, fieldName, true, fieldsToIndex);
        } else if ("false".equalsIgnoreCase(stringValue)) {
            addFieldToSolrDocument(inputDocument, fieldName, false, fieldsToIndex);
        } else {
            addFieldToSolrDocument(inputDocument, fieldName, stringValue, fieldsToIndex);
        }
        break;
    case RECORD: {
        final Record record = (Record) coercedValue;
        writeRecord(record, inputDocument, fieldsToIndex, fieldName);
        break;
    }
    case ARRAY:
    default:
        if (coercedValue instanceof Object[]) {
            final Object[] values = (Object[]) coercedValue;
            for (Object element : values) {
                if (element instanceof Record) {
                    writeRecord((Record) element, inputDocument, fieldsToIndex, fieldName);
                } else {
                    addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex);
                }
            }
        } else {
            addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex);
        }
        break;
    }
}

From source file:net.resheim.eclipse.timekeeper.ui.Activator.java

private void installTaxameter() {

    switch (Platform.getOS()) {
    case Platform.OS_MACOSX:
        detector = new MacIdleTimeDetector();
        break;/*w  ww .j  av  a  2s.  c  o m*/
    case Platform.OS_LINUX:
        detector = new X11IdleTimeDetector();
        break;
    case Platform.OS_WIN32:
        detector = new WindowsIdleTimeDetector();
        break;
    default:
        detector = new GenericIdleTimeDetector();
        break;
    }

    Timer timer = new Timer("Timekeeper", true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (!PlatformUI.getWorkbench().isClosing()) {
                long idleTimeMillis = detector.getIdleTimeMillis();
                ITask task = TasksUi.getTaskActivityManager().getActiveTask();
                if (null != task) {
                    if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
                        // Was idle on last check, reactivate
                        Display.getDefault().syncExec(() -> handleReactivation(idleTimeMillis));
                    } else if (lastIdleTime < IDLE_INTERVAL) {
                        String tickString = Activator.getValue(task, Activator.TICK);
                        LocalDateTime now = LocalDateTime.now();
                        LocalDateTime ticked = LocalDateTime.parse(tickString);
                        // Currently not idle so accumulate spent time
                        accumulateTime(task, now.toLocalDate().toString(),
                                ticked.until(now, ChronoUnit.MILLIS));
                        Activator.setValue(task, Activator.TICK, now.toString());
                    }
                }
                lastIdleTime = idleTimeMillis;
            }
        }
    }, SHORT_INTERVAL, SHORT_INTERVAL);

    // Immediately run the idle handler if the system has been idle and
    // the user has pressed a key or mouse button _inside_ the running
    // application.
    reactivationListener = new Listener() {
        public void handleEvent(Event event) {
            long idleTimeMillis = detector.getIdleTimeMillis();
            if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
                handleReactivation(idleTimeMillis);
            }
            lastIdleTime = idleTimeMillis;
        }
    };
    final Display display = PlatformUI.getWorkbench().getDisplay();
    display.addFilter(SWT.KeyUp, reactivationListener);
    display.addFilter(SWT.MouseUp, reactivationListener);
}