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.linkedin.cubert.utils.FileSystemUtils.java

License:Open Source License

public static List<Path> getPaths(FileSystem fs, JsonNode json, boolean schemaOnly, JsonNode params)
        throws IOException {
    if (json.isArray()) {
        List<Path> paths = new ArrayList<Path>();
        // If the specified input is array, recursively get paths for each item in the
        // array/* ww  w.ja  v  a2  s  .  c  om*/
        ArrayNode anode = (ArrayNode) json;
        for (int i = 0; i < anode.size(); i++) {
            paths.addAll(getPaths(fs, json.get(i), params));
        }
        return paths;
    } else if (json.isTextual()) {
        return getPaths(fs, new Path(json.getTextValue()));
    } else {
        List<Path> paths = new ArrayList<Path>();
        Path root = new Path(getText(json, "root"));
        Path basePath = root;
        JsonNode startDateJson = json.get("startDate");
        if (schemaOnly && json.get("origStartDate") != null)
            startDateJson = json.get("origStartDate");

        JsonNode endDateJson = json.get("endDate");
        if (startDateJson == null || endDateJson == null) {
            throw new IllegalArgumentException("StartDate and endDate need to be specified");
        }
        String startDuration, endDuration;
        if (startDateJson.isTextual()) {
            startDuration = startDateJson.getTextValue();
            endDuration = endDateJson.getTextValue();
        }

        else {
            startDuration = startDateJson.toString();
            endDuration = endDateJson.toString();
        }

        boolean errorOnMissing = false;
        JsonNode errorOnMissingJson = params.get("errorOnMissing");
        if (errorOnMissingJson != null)
            errorOnMissing = Boolean.parseBoolean(errorOnMissingJson.getTextValue());

        boolean useHourlyForMissingDaily = false;
        JsonNode useHourlyForMissingDailyJson = params.get("useHourlyForMissingDaily");
        if (useHourlyForMissingDailyJson != null)
            useHourlyForMissingDaily = Boolean.parseBoolean(useHourlyForMissingDailyJson.getTextValue());

        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMdd");
        DateTimeFormatter dtfwHour = DateTimeFormat.forPattern("yyyyMMddHH");
        DateTime startDate, endDate;
        boolean isDaily;
        int hourStep;
        if (startDuration.length() == 8) {
            if (endDuration.length() != 8)
                throw new IllegalArgumentException(
                        "EndDate " + endDuration + " is not consistent with StartDate " + startDuration);
            startDate = dtf.parseDateTime(startDuration);
            endDate = dtf.parseDateTime(endDuration);
            isDaily = true;
            hourStep = 24;
        } else if (startDuration.length() == 10) {
            if (endDuration.length() != 10)
                throw new IllegalArgumentException(
                        "EndDate " + endDuration + " is not consistent with StartDate " + startDuration);
            startDate = dtfwHour.parseDateTime(startDuration);
            endDate = dtfwHour.parseDateTime(endDuration);
            isDaily = false;
            hourStep = 1;
        } else {
            throw new IllegalArgumentException(
                    "Cannot parse StartDate " + startDuration + " as daily or hourly duration");

        }

        for (Path path : getPaths(fs, root)) {
            if (isDaily) {
                if (path.getName().equals("daily"))
                    basePath = path;
                else
                    basePath = new Path(path, "daily");
            } else {
                if (path.getName().equals("hourly"))
                    basePath = path;
                else
                    basePath = new Path(path, "hourly");
            }

            //If daily folder itself doesn't exist
            if (!fs.exists(basePath) && isDaily && useHourlyForMissingDaily
                    && fs.exists(new Path(basePath.getParent(), "hourly"))) {
                basePath = new Path(basePath.getParent(), "hourly");
                endDate = endDate.plusHours(23);
                isDaily = false;
                hourStep = 1;
            }

            paths.addAll(getDurationPaths(fs, basePath, startDate, endDate, isDaily, hourStep, errorOnMissing,
                    useHourlyForMissingDaily));
        }

        if (paths.isEmpty() && schemaOnly)
            throw new IOException(String.format("No input files at %s from %s to %s", basePath.toString(),
                    startDuration, endDuration));
        return paths;
    }

}

From source file:com.lithium.yoda.ToEpoch.java

License:Apache License

@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
    if (dateOi instanceof StringObjectInspector) {
        String dateStr = ((StringObjectInspector) dateOi).getPrimitiveJavaObject(arguments[0].get());
        DateTimeFormatter dtf;
        if (hasSecondArg) {
            if (constSecondArg == null) {
                dtf = DateTimeFormat.forPattern(formatOi.getPrimitiveJavaObject(arguments[1].get()));
            } else {
                dtf = DateTimeFormat.forPattern(constSecondArg);
            }/*from  w ww .j av  a2 s .c o  m*/
        } else {
            dtf = ISODateTimeFormat.dateTimeParser().withOffsetParsed();
        }
        return dtf.parseDateTime(dateStr).getMillis();
    } else if (dateOi instanceof TimestampObjectInspector) {
        Timestamp ts = ((TimestampObjectInspector) dateOi).getPrimitiveJavaObject(arguments[0].get());
        if (hasSecondArg) {
            DateTime dt;
            if (constSecondArg == null) {
                dt = new DateTime(ts.getTime(),
                        DateTimeZone.forID(formatOi.getPrimitiveJavaObject(arguments[1].get())));
            } else {
                dt = new DateTime(ts.getTime(), DateTimeZone.forID(constSecondArg));
            }
            return dt.getMillis();
        } else {
            return ts.getTime();
        }
    }

    return null;
}

From source file:com.loadtesting.showcase.springmvc.model.converter.JodaTimeConverter.java

License:Apache License

public JodaTimeForm convert(JodaTimeForm form) throws ParseException {
    DateTimeFormatter format1 = getFormat(form.getFromTimeZone());
    DateTime date = format1.parseDateTime(form.getInputDate());
    DateTimeFormatter format2 = getFormat(form.getToTimeZone());
    String outputDate = format2.print(date);
    JodaTimeForm resultForm = new JodaTimeForm();
    resultForm.setInputDate(form.getInputDate());
    resultForm.setFromTimeZone(form.getFromTimeZone());
    resultForm.setToTimeZone(form.getToTimeZone());
    resultForm.setOutputDate(outputDate);
    return resultForm;
}

From source file:com.manydesigns.elements.util.Util.java

License:Open Source License

public static DateTime parseDateTime(DateTimeFormatter dateTimeFormatter, String input, boolean withTime) {
    if (withTime) {
        return dateTimeFormatter.parseDateTime(input);
    } else {/*from   w w  w  .  j a va  2 s . com*/
        LocalDate localDate = dateTimeFormatter.parseLocalDate(input);
        return localDate.toDateTimeAtStartOfDay();
    }
}

From source file:com.metabroadcast.common.social.auth.ictomorrow.ICTomorrowApiHelper.java

private ICTomorrowItemMetadata getItem(Element itemElement) {
    Integer contentHandle = Integer.valueOf(itemElement.getAttributeValue("ContentHandle"));
    String contentKey = itemElement.getFirstChildElement("Key").getValue().trim();

    ICTomorrowItemMetadata item = new ICTomorrowItemMetadata(contentHandle, contentKey);

    item.setChannelTitle(getCharacteristic(itemElement, "Channel-Title"));
    String link = getCharacteristic(itemElement, "Link");
    if (link == null) {
        link = getCharacteristic(itemElement, "URL Location");
    }//from ww  w.  ja  v a  2s .c  om
    item.setLink(link);
    item.setSource(getCharacteristic(itemElement, "Source"));
    item.setWebmaster(getCharacteristic(itemElement, "WebMaster"));
    item.setTitle(getOptionalValue(itemElement, "Title"));
    item.setContentProvider(getOptionalValue(itemElement, "ContentProvider"));
    item.setLicenceTemplateName(getOptionalValue(itemElement, "LicenseTemplateName"));

    String keywords = getCharacteristic(itemElement, "Keywords");
    if (keywords != null) {
        item.setKeywords(
                ImmutableSet.copyOf(Splitter.on(",").trimResults().omitEmptyStrings().split(keywords)));
    }

    String dateString = getCharacteristic(itemElement, "Pub-date");
    if (dateString != null) {
        DateTimeFormatter dateParser = new DateTimeFormatterBuilder().appendDayOfWeekShortText()
                .appendLiteral(", ").appendDayOfMonth(2).appendLiteral(" ").appendMonthOfYearShortText()
                .appendLiteral(" ").appendYear(4, 4).appendLiteral(" ").appendHourOfDay(2).appendLiteral(":")
                .appendMinuteOfHour(2).appendLiteral(":").appendSecondOfMinute(2).appendLiteral(" GMT")
                .toFormatter();
        //DateTimeFormat.forPattern("E, dd MM yyyy HH:mm:ss z");

        DateTime date = dateParser.parseDateTime(dateString);

        item.setPublishedDate(date);
    }

    return item;
}

From source file:com.metamx.common.parsers.TimestampParser.java

License:Apache License

public static Function<String, DateTime> createTimestampParser(final String format) {
    if (format.equalsIgnoreCase("auto")) {
        // Could be iso or millis
        return new Function<String, DateTime>() {
            @Override//from ww  w .  j  a  va  2 s .  co  m
            public DateTime apply(String input) {
                Preconditions.checkArgument(input != null && !input.isEmpty(), "null timestamp");

                for (int i = 0; i < input.length(); i++) {
                    if (input.charAt(i) < '0' || input.charAt(i) > '9') {
                        return new DateTime(ParserUtils.stripQuotes(input));
                    }
                }

                return new DateTime(Long.parseLong(input));
            }
        };
    } else if (format.equalsIgnoreCase("iso")) {
        return new Function<String, DateTime>() {
            @Override
            public DateTime apply(String input) {
                Preconditions.checkArgument(input != null && !input.isEmpty(), "null timestamp");
                return new DateTime(ParserUtils.stripQuotes(input));
            }
        };
    } else if (format.equalsIgnoreCase("posix") || format.equalsIgnoreCase("millis")
            || format.equalsIgnoreCase("nano")) {
        final Function<Number, DateTime> numericFun = createNumericTimestampParser(format);
        return new Function<String, DateTime>() {
            @Override
            public DateTime apply(String input) {
                Preconditions.checkArgument(input != null && !input.isEmpty(), "null timestamp");
                return numericFun.apply(Long.parseLong(ParserUtils.stripQuotes(input)));
            }
        };
    } else if (format.equalsIgnoreCase("ruby")) {
        // Numeric parser ignores millis for ruby.
        final Function<Number, DateTime> numericFun = createNumericTimestampParser(format);
        return new Function<String, DateTime>() {
            @Override
            public DateTime apply(String input) {
                Preconditions.checkArgument(input != null && !input.isEmpty(), "null timestamp");
                return numericFun.apply(Double.parseDouble(ParserUtils.stripQuotes(input)));
            }
        };
    } else {
        try {
            final DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
            return new Function<String, DateTime>() {
                @Override
                public DateTime apply(String input) {
                    Preconditions.checkArgument(input != null && !input.isEmpty(), "null timestamp");
                    return formatter.parseDateTime(ParserUtils.stripQuotes(input));
                }
            };
        } catch (Exception e) {
            throw new IAE(e, "Unable to parse timestamps with format [%s]", format);
        }
    }
}

From source file:com.money.manager.ex.investment.PriceCsvParser.java

License:Open Source License

/**
 * Parses CSV content and fires an PriceDownloadedEvent.
 * @param content CSV content to parse into price information.
 *//*from  w w w  . ja  va2s.  c  om*/
public PriceDownloadedEvent parse(String content) {
    // cleanup
    content = content.trim();

    // validation
    if (TextUtils.isEmpty(content)) {
        throw new IllegalArgumentException("Downloaded CSV contents are empty");
    }

    // parse CSV contents to get proper fields that can be saved to the database.
    CSVParser csvParser = new CSVParser();
    String[] values;
    try {
        values = csvParser.parseLineMulti(content);
    } catch (IOException e) {
        Timber.e(e, "parsing downloaded CSV contents");
        return null;
    }

    // convert csv values to their original type.

    String symbol = values[0];

    // price
    String priceString = values[1];
    if (!NumericHelper.isNumeric(priceString))
        return null;
    Money price = MoneyFactory.fromString(priceString);
    // LSE stocks are expressed in GBp (pence), not Pounds.
    // From stockspanel.cpp, line 785: if (StockQuoteCurrency == "GBp") dPrice = dPrice / 100;
    String currency = values[3];
    if (currency.equals("GBp")) {
        price = price.divide(100, MoneyFactory.MAX_ALLOWED_PRECISION);
    }

    // date
    DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy");
    DateTime date = format.parseDateTime(values[2]);

    // Note: For currencies, the symbol is i.e. AUDEUR=X

    return new PriceDownloadedEvent(symbol, price, date);
}

From source file:com.money.manager.ex.investment.yql.YqlSecurityPriceUpdaterRetrofit.java

License:Open Source License

private SecurityPriceModel getSecurityPriceFor(JsonObject quote) {
    SecurityPriceModel priceModel = new SecurityPriceModel();
    priceModel.symbol = quote.get("symbol").getAsString();

    ExceptionHandler handler = new ExceptionHandler(getContext(), this);

    // Price/* ww  w .j a  va  2 s . c om*/

    JsonElement priceElement = quote.get("LastTradePriceOnly");
    if (priceElement == JsonNull.INSTANCE) {
        handler.showMessage(
                getContext().getString(R.string.error_no_price_found_for_symbol) + " " + priceModel.symbol);
        return null;
    }
    String priceString = priceElement.getAsString();
    if (!NumericHelper.isNumeric(priceString)) {
        handler.showMessage(
                getContext().getString(R.string.error_no_price_found_for_symbol) + " " + priceModel.symbol);
        return null;
    }

    priceModel.price = readPrice(priceString, quote);

    // Date

    DateTime date = MmxDateTimeUtils.today();
    JsonElement dateElement = quote.get("LastTradeDate");
    if (dateElement != JsonNull.INSTANCE) {
        // Sometimes the date is not available. For now we will use today's date.
        DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy");
        date = format.parseDateTime(dateElement.getAsString());
    }
    priceModel.date = date;

    return priceModel;
}

From source file:com.money.manager.ex.search.OnDateButtonClickListener.java

License:Open Source License

@Override
public void onClick(View v) {
    DateTime dateTime = MmxDateTimeUtils.today();
    String calendarValue = mTextView.getText().toString();

    if (!TextUtils.isEmpty(calendarValue)) {
        String userDatePattern = new MmxDateTimeUtils(mParent.getApplicationContext()).getUserDatePattern();
        DateTimeFormatter formatter = DateTimeFormat.forPattern(userDatePattern);
        dateTime = formatter.parseDateTime(calendarValue);
    }/*from  www .  ja  v a2s  .  co  m*/

    CalendarDatePickerDialogFragment datePicker = new CalendarDatePickerDialogFragment()
            .setFirstDayOfWeek(MmxDateTimeUtils.getFirstDayOfWeek()).setOnDateSetListener(mDateSetListener)
            .setPreselectedDate(dateTime.getYear(), dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth());
    if (new UIHelper(mParent).isDarkTheme()) {
        datePicker.setThemeDark();
    }
    datePicker.show(mParent.getSupportFragmentManager(), DATEPICKER_TAG);
}

From source file:com.money.manager.ex.settings.BehaviourSettingsFragment.java

License:Open Source License

private void showTimePicker() {
    final BehaviourSettings settings = new BehaviourSettings(getActivity());

    RadialTimePickerDialogFragment.OnTimeSetListener timeSetListener = new RadialTimePickerDialogFragment.OnTimeSetListener() {
        @Override//w w w. j a va2s.co  m
        public void onTimeSet(RadialTimePickerDialogFragment dialog, int hourOfDay, int minute) {
            String value = String.format("%02d:%02d", hourOfDay, minute);
            settings.setNotificationTime(value);
        }
    };

    // get time to display (current setting)
    String timeString = settings.getNotificationTime();
    DateTimeFormatter formatter = DateTimeFormat.forPattern(Constants.TIME_FORMAT);
    DateTime currentValue = formatter.parseDateTime(timeString);

    int hour = currentValue != null ? currentValue.getHourOfDay() : 8;
    int minute = currentValue != null ? currentValue.getMinuteOfHour() : 0;

    RadialTimePickerDialogFragment timePicker = new RadialTimePickerDialogFragment()
            .setOnTimeSetListener(timeSetListener).setStartTime(hour, minute).setThemeDark();
    timePicker.show(getChildFragmentManager(), KEY_NOTIFICATION_TIME);
}