Example usage for org.joda.time.format DateTimeFormatter parseDateTime

List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseDateTime.

Prototype

public DateTime parseDateTime(String text) 

Source Link

Document

Parses a date-time from the given text, returning a new DateTime.

Usage

From source file:com.money.manager.ex.utils.MmxDateTimeUtils.java

License:Open Source License

public static DateTime from(String dateString, String pattern) {
    if (TextUtils.isEmpty(dateString))
        return null;

    DateTimeFormatter format = DateTimeFormat.forPattern(pattern);
    //        DateTime dateTime = format.parseDateTime(dateString);
    DateTime dateTime = format // .withZoneUTC()
            .parseDateTime(dateString);//w  w  w.  jav a 2 s . c o  m
    return dateTime;
}

From source file:com.moosemorals.weather.xml.WeatherParser.java

License:Open Source License

private DailyForecast readForecast(XMLStreamReader parser, WeatherReport.Builder reportBuilder, DateTime when)
        throws XMLStreamException, IOException {
    parser.require(XMLStreamReader.START_ELEMENT, NAMESPACE, "weather");

    DailyForecast.Builder builder = new DailyForecast.Builder();

    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd").withZone(when.getZone());

    while (parser.next() != XMLStreamReader.END_ELEMENT) {
        if (parser.getEventType() != XMLStreamReader.START_ELEMENT) {
            continue;
        }/*w w  w  .jav a2s. c o  m*/

        switch (parser.getLocalName()) {
        case "date":
            builder.setDate(fmt.parseDateTime(readTag(parser, "date")));
            break;
        case "astronomy":
            builder.setAstronomy(readAstronmy(parser, when));
            break;
        case "maxtempC":
            builder.setMaxTempC(readIntTag(parser, "maxtempC"));
            break;
        case "maxtempF":
            builder.setMaxTempF(readIntTag(parser, "maxtempF"));
            break;
        case "mintempC":
            builder.setMinTempC(readIntTag(parser, "mintempC"));
            break;
        case "mintempF":
            builder.setMinTempF(readIntTag(parser, "mintempF"));
            break;
        case "uvIndex":
            builder.setUvIndex(readIntTag(parser, "uvIndex"));
            break;
        case "hourly":
            reportBuilder.addHourlyForecast(readHour(parser));
            break;
        default:
            log.warn("Forecast: Skiping unexpected tag {}", parser.getLocalName());
            skipTag(parser);
            break;
        }
    }

    return builder.build();
}

From source file:com.moosemorals.weather.xml.WeatherParser.java

License:Open Source License

protected DateTime readTimeZone(XMLStreamReader parser) throws XMLStreamException, IOException {
    parser.require(XMLStreamReader.START_ELEMENT, NAMESPACE, "time_zone");

    String rawDate = null;// w  w w . j a  v a 2s  .c  om
    float utcOffset = 0.0f;

    while (parser.next() != XMLStreamReader.END_ELEMENT) {
        if (parser.getEventType() != XMLStreamReader.START_ELEMENT) {
            continue;
        }

        String raw;
        switch (parser.getLocalName()) {
        case "localtime":
            rawDate = readTag(parser, "localtime");
            break;
        case "utcOffset":
            utcOffset = readFloatTag(parser, "utcOffset");
            break;
        }
    }

    int hoursOffset = (int) utcOffset;
    int minutesOffset = (int) ((utcOffset - hoursOffset) * 60.0);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm")
            .withZone(DateTimeZone.forOffsetHoursMinutes(hoursOffset, minutesOffset));

    return fmt.parseDateTime(rawDate);
}

From source file:com.moss.joda.swing.JodaOptionPane.java

License:Open Source License

private static TimeOfDay parseTime(String text) {
    if (text == null || text.trim().length() == 0) {
        return null;
    } else {/*from   w w w.  j  av  a2s .c om*/
        DateTime paddedTime = null;
        for (DateTimeFormatter format : timeFormats) {
            try {
                paddedTime = format.parseDateTime(text);
            } catch (IllegalArgumentException e) {
                // just means the text is no good.
            }
        }

        if (paddedTime == null)
            throw new RuntimeException("Unparsable time: " + text);

        return new TimeOfDay(paddedTime.getHourOfDay(), paddedTime.getMinuteOfHour(),
                paddedTime.getSecondOfMinute());
    }
}

From source file:com.moss.joda.swing.LiveDatePicker.java

License:Open Source License

public LiveDatePicker() {
    formats.add(DateTimeFormat.shortDate());
    formats.add(ISODateTimeFormat.date());
    formats.add(ISODateTimeFormat.basicDate());
    formats.add(DateTimeFormat.mediumDate());
    formats.add(DateTimeFormat.fullDate());
    formats.add(DateTimeFormat.longDate());

    //      p = new JXDatePicker();
    //      pButton = p.getComponent(1);
    //      p.getEditor().setVisible(false);

    pButton = new JButton("^");
    pButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Point p = pButton.getLocation();
            popup.show(pButton, 0, 0);//from  w  w  w  .  j a v  a2 s . c  o  m

        }
    });
    popup.add(new DateSelectionListener() {
        public void dateSelected(YearMonthDay date) {
            setDate(date);
            fireSelection();
        }
    });

    t.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            handle();
        }

        public void insertUpdate(DocumentEvent e) {
            handle();
        }

        public void removeUpdate(DocumentEvent e) {
            handle();
        }

        void handle() {
            if (!uiUpdating) {
                String text = t.getText();
                YearMonthDay date = null;
                for (int x = 0; date == null && x < formats.size(); x++) {
                    DateTimeFormatter f = formats.get(x);
                    try {
                        date = f.parseDateTime(text).toYearMonthDay();
                    } catch (IllegalArgumentException e) {
                    }
                }
                value = date;
                if (date != null) {
                    popup.setDate(date);
                }
                fireSelection();
            }
        }

    });

    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1;
    c.ipadx = 10;
    add(t, c);
    c.weightx = 0;
    c.ipadx = 0;
    //      c.insets.left = 5;
    add(pButton, c);

    setDate(new YearMonthDay());
}

From source file:com.moss.maven.util.MavenPomPropertiesDateFormatter.java

License:Open Source License

public DateTime parseDateTime(String mavenFormattedDateAndTime) {

    // THE JODA PARSER DOESN'T HANDLE TIMEZONES WELL, SO WE'RE PULLING THE ZONE OUT AND PARSING IT SEPARATELY
    int length = mavenFormattedDateAndTime.length();
    String timezoneText = mavenFormattedDateAndTime.substring(length - 8, length - 5).trim();
    String yearText = mavenFormattedDateAndTime.substring(length - 4).trim();
    String jodaParseableText = mavenFormattedDateAndTime.substring(0, length - 8).trim() + " " + yearText;

    // PARSE THE ZONE
    DateTimeZone timeZone;/*from w  w w .j av a2  s.  c  om*/
    if ("EDT".equals(timezoneText))
        timeZone = DateTimeZone.forID("America/New_York");
    else
        timeZone = DateTimeZone.forID(timezoneText);

    // PARSE THE STRING WITHOUT THE ZONE INFO
    DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss YYYY");
    DateTime dateTime = fmt.parseDateTime(jodaParseableText);

    // ADD THE ZONE BACK
    dateTime = new DateTime(dateTime.getMillis(), timeZone);

    return dateTime;
}

From source file:com.mycollab.common.service.impl.TimelineTrackingServiceImpl.java

License:Open Source License

@Override
public Map<String, List<GroupItem>> findTimelineItems(String fieldGroup, List<String> groupVals, Date start,
        Date end, TimelineTrackingSearchCriteria criteria) {
    try {/*from  w  ww  . ja v  a2 s . com*/
        DateTime startDate = new DateTime(start);
        final DateTime endDate = new DateTime(end);
        if (startDate.isAfter(endDate)) {
            throw new UserInvalidInputException("Start date must be greaterThan than end date");
        }
        List<Date> dates = boundDays(startDate, endDate.minusDays(1));
        Map<String, List<GroupItem>> items = new HashMap<>();
        criteria.setFieldgroup(StringSearchField.and(fieldGroup));
        List<GroupItem> cacheTimelineItems = timelineTrackingCachingMapperExt.findTimelineItems(groupVals,
                dates, criteria);

        DateTime calculatedDate = startDate.toDateTime();
        if (cacheTimelineItems.size() > 0) {
            GroupItem item = cacheTimelineItems.get(cacheTimelineItems.size() - 1);
            String dateValue = item.getGroupname();
            calculatedDate = DateTime.parse(dateValue, DateTimeFormat.forPattern("yyyy-MM-dd"));

            for (GroupItem map : cacheTimelineItems) {
                String groupVal = map.getGroupid();
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(map);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(map);
                }
            }
        }

        dates = boundDays(calculatedDate.plusDays(1), endDate);
        if (dates.size() > 0) {
            boolean isValidForBatchSave = true;
            final Set<String> types = criteria.getTypes().getValues();
            SetSearchField<Integer> extraTypeIds = criteria.getExtraTypeIds();
            Integer tmpExtraTypeId = null;
            if (extraTypeIds != null) {
                if (extraTypeIds.getValues().size() == 1) {
                    tmpExtraTypeId = extraTypeIds.getValues().iterator().next();
                } else {
                    isValidForBatchSave = false;
                }
            }
            final Integer extraTypeId = tmpExtraTypeId;

            final List<Map> timelineItems = timelineTrackingMapperExt.findTimelineItems(groupVals, dates,
                    criteria);
            if (isValidForBatchSave) {
                final Integer sAccountId = (Integer) criteria.getSaccountid().getValue();
                final String itemFieldGroup = criteria.getFieldgroup().getValue();
                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

                final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
                final List<Map> filterCollections = new ArrayList<>(
                        Collections2.filter(timelineItems, input -> {
                            String dateStr = (String) input.get("groupname");
                            DateTime dt = formatter.parseDateTime(dateStr);
                            return !dt.equals(endDate);
                        }));
                jdbcTemplate.batchUpdate(
                        "INSERT INTO `s_timeline_tracking_cache`(type, fieldval,extratypeid,sAccountId,"
                                + "forDay, fieldgroup,count) VALUES(?,?,?,?,?,?,?)",
                        new BatchPreparedStatementSetter() {
                            @Override
                            public void setValues(PreparedStatement preparedStatement, int i)
                                    throws SQLException {
                                Map item = filterCollections.get(i);
                                //                            preparedStatement.setString(1, types);
                                String fieldVal = (String) item.get("groupid");
                                preparedStatement.setString(2, fieldVal);
                                preparedStatement.setInt(3, extraTypeId);
                                preparedStatement.setInt(4, sAccountId);
                                String dateStr = (String) item.get("groupname");
                                DateTime dt = formatter.parseDateTime(dateStr);
                                preparedStatement.setDate(5, new java.sql.Date(dt.toDate().getTime()));
                                preparedStatement.setString(6, itemFieldGroup);
                                int value = ((BigDecimal) item.get("value")).intValue();
                                preparedStatement.setInt(7, value);
                            }

                            @Override
                            public int getBatchSize() {
                                return filterCollections.size();
                            }
                        });
            }

            for (Map map : timelineItems) {
                String groupVal = (String) map.get("groupid");
                GroupItem item = new GroupItem();
                item.setValue(((BigDecimal) map.get("value")).doubleValue());
                item.setGroupid((String) map.get("groupid"));
                item.setGroupname((String) map.get("groupname"));
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(item);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(item);
                }
            }
        }

        return items;
    } catch (Exception e) {
        LOG.error("Error", e);
        return null;
    }
}

From source file:com.nesscomputing.syslog4j.server.impl.event.structured.StructuredSyslogServerEvent.java

License:Open Source License

protected void parseDate() {
    // skip VERSION field
    int i = this.message.indexOf(' ');
    this.message = this.message.substring(i + 1);

    // parse the date
    i = this.message.indexOf(' ');

    if (i > -1) {
        String dateString = StringUtils.trimToEmpty(this.message.substring(0, i));

        try {// ww w  . java 2  s  .  c  om
            DateTimeFormatter formatter = getDateTimeFormatter();

            this.dateTime = formatter.parseDateTime(dateString);
            this.date = this.dateTime.toDate();

            this.message = this.message.substring(dateString.length() + 1);

        } catch (Exception e) {
            // Not structured date format, try super one
            super.parseDate();
        }
    }
}

From source file:com.netflix.dynomitemanager.sidecore.backup.S3Restore.java

License:Apache License

private long restoreTime(String dateString) {
    logger.info("Date to restore to: " + dateString);

    DateTimeFormatter formatter = null;
    try {//from   ww  w.j a  v a  2s .com
        formatter = DateTimeFormat.forPattern("yyyyMMdd");
    } catch (Exception e) {
        logger.error("Restore fast property not formatted properly " + e.getMessage());
        return -1;
    }

    DateTime dt = formatter.parseDateTime(dateString);
    DateTime dateBackup = dt.withTimeAtStartOfDay();
    return dateBackup.getMillis();

}

From source file:com.nominanuda.lang.DateTimeHelper.java

License:Apache License

/**
 * @return the millis from epoch GMT or -1 if format is not recognized
 *//*  www. j a  v a  2 s  .c o  m*/
public long parseHttpDate822(String val) {
    val = val.trim();
    if (val.endsWith(" GMT")) {
        val = val.substring(0, val.length() - 4);
    }
    for (DateTimeFormatter fmt : STD_RFC_822_FMTS) {
        try {
            return fmt.parseDateTime(val).getMillis();
        } catch (IllegalArgumentException e) {
        }
    }
    for (DateTimeFormatter fmt : NON_STD_RFC_822_FMTS) {
        try {
            return fmt.parseDateTime(val).getMillis();
        } catch (IllegalArgumentException e) {
        }
    }
    return -1;
}