Example usage for org.joda.time.format ISODateTimeFormat dateTimeParser

List of usage examples for org.joda.time.format ISODateTimeFormat dateTimeParser

Introduction

In this page you can find the example usage for org.joda.time.format ISODateTimeFormat dateTimeParser.

Prototype

public static DateTimeFormatter dateTimeParser() 

Source Link

Document

Returns a generic ISO datetime parser which parses either a date or a time or both.

Usage

From source file:in.dream_lab.eventgen.factory.LoadCsvToMemory.java

License:Apache License

public static ArrayList<RowClass> loadListFromCSV(String csvFileName) throws IOException {
    CSVReader reader = new CSVReader(new FileReader(csvFileName));
    String[] nextLine;//from  www.  j a v a  2s  . com
    int ctr = 0;
    String[] headers = reader.readNext(); //use .intern() later
    ArrayList<RowClass> arr = new ArrayList<RowClass>();

    while ((nextLine = reader.readNext()) != null) {
        // nextLine[] is an array of values from the line
        //System.out.println(nextLine[0] +  "  "  + nextLine[1] + "   " + nextLine[2] + "  " + nextLine[3]  + "  etc...");

        HashMap<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < nextLine.length; i++) {
            map.put(headers[i], nextLine[i]);
        }
        DateTime date = ISODateTimeFormat.dateTimeParser().parseDateTime(nextLine[0]);
        long ts = date.getMillis();
        RowClass rowClass = new RowClass(ts, map);
        arr.add(rowClass);

        ctr++;
    }

    return arr;
}

From source file:influent.server.utilities.DateTimeParser.java

License:MIT License

/**
 * @see http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#parse(java.lang.String)
 *///from w  w  w. ja v  a2s.c  o  m
public static DateTime parse(String str) {
    if (str == null || str.isEmpty())
        return null;

    // if we can, just pick out the date because we need to ignore any time zone information.
    if (str.length() >= 10) {
        try {
            int yyyy = Integer.parseInt(str.substring(0, 4));
            int mm = Integer.parseInt(str.substring(5, 7));
            int dd = Integer.parseInt(str.substring(8, 10));

            // extra sanity check
            switch (str.charAt(4)) {
            case '-':
            case '/':
                return new DateTime(yyyy, mm, dd, 0, 0, 0, DateTimeZone.UTC);
            }

        } catch (Exception e) {
        }
    }

    final DateTime d = ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(str);

    return new DateTime(d.getYear(), d.getMonthOfYear(), d.getDayOfMonth(), 0, 0, 0, DateTimeZone.UTC);
}

From source file:io.druid.query.expression.TimestampParseExprMacro.java

License:Apache License

@Override
public Expr apply(final List<Expr> args) {
    if (args.size() < 1 || args.size() > 3) {
        throw new IAE("Function[%s] must have 1 to 3 arguments", name());
    }/*ww w . j  a v  a 2 s .co m*/

    final Expr arg = args.get(0);
    final String formatString = args.size() > 1 ? (String) args.get(1).getLiteralValue() : null;
    final DateTimeZone timeZone;

    if (args.size() > 2 && args.get(2).getLiteralValue() != null) {
        timeZone = DateTimeZone.forID((String) args.get(2).getLiteralValue());
    } else {
        timeZone = DateTimeZone.UTC;
    }

    final DateTimeFormatter formatter = formatString == null ? ISODateTimeFormat.dateTimeParser()
            : DateTimeFormat.forPattern(formatString).withZone(timeZone);

    class TimestampParseExpr implements Expr {
        @Nonnull
        @Override
        public ExprEval eval(final ObjectBinding bindings) {
            try {
                return ExprEval.of(formatter.parseDateTime(arg.eval(bindings).asString()).getMillis());
            } catch (IllegalArgumentException e) {
                // Catch exceptions potentially thrown by formatter.parseDateTime. Our docs say that unparseable timestamps
                // are returned as nulls.
                return ExprEval.of(null);
            }
        }

        @Override
        public void visit(final Visitor visitor) {
            arg.visit(visitor);
            visitor.visit(this);
        }
    }

    return new TimestampParseExpr();
}

From source file:io.prestosql.operator.scalar.DateTimeFunctions.java

License:Apache License

@ScalarFunction("from_iso8601_timestamp")
@LiteralParameters("x")
@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE)
public static long fromISO8601Timestamp(ConnectorSession session,
        @SqlType("varchar(x)") Slice iso8601DateTime) {
    DateTimeFormatter formatter = ISODateTimeFormat.dateTimeParser()
            .withChronology(getChronology(session.getTimeZoneKey())).withOffsetParsed();
    return packDateTimeWithZone(parseDateTimeHelper(formatter, iso8601DateTime.toStringUtf8()));
}

From source file:it.cineca.pst.huborcid.domain.util.CustomDateTimeDeserializer.java

License:Open Source License

@Override
public DateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken t = jp.getCurrentToken();/*from  w  w w  .  ja  va2 s.c o  m*/
    if (t == JsonToken.VALUE_STRING) {
        String str = jp.getText().trim();
        return ISODateTimeFormat.dateTimeParser().parseDateTime(str);
    }
    if (t == JsonToken.VALUE_NUMBER_INT) {
        return new DateTime(jp.getLongValue());
    }
    throw ctxt.mappingException(handledType());
}

From source file:it.cineca.pst.huborcid.domain.util.ISO8601LocalDateDeserializer.java

License:Open Source License

@Override
public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken t = jp.getCurrentToken();//from   w ww . j a v  a2  s  . c o  m
    if (t == JsonToken.VALUE_STRING) {
        String str = jp.getText().trim();
        return ISODateTimeFormat.dateTimeParser().parseLocalDate(str);
    }
    if (t == JsonToken.VALUE_NUMBER_INT) {
        return new LocalDate(jp.getLongValue());
    }
    throw ctxt.mappingException(handledType());
}

From source file:it.tidalwave.northernwind.rca.util.PropertyUtilities.java

License:Apache License

/*******************************************************************************************************************
 *
 * Returns a 'fixed' value for a property. ResourceProperties at the moment manages each property as a string.
 * This method converts them in the proper type.
 *
 * @param       properties          the properties to read
 * @param       key                 the key
 * @return                          the value
 * @throws      NotFoundException   if the key is not found
 *
 ******************************************************************************************************************/
@Nonnull//  www. j  av  a 2  s . c om
public static Object getFixedPropertyValue(final @Nonnull ResourceProperties properties,
        final @Nonnull Key<?> key) throws NotFoundException, IOException {
    Object property = properties.getProperty(key);

    // FIXME: should be done by ResourceProperties and get the type from key, but it's not yet supported
    if (key.stringValue().endsWith("DateTime")) {
        property = ISODateTimeFormat.dateTimeParser().parseDateTime(property.toString());
    }

    return property;
}

From source file:net.ftlines.wicket.fullcalendar.callback.ViewDisplayCallback.java

License:Apache License

@Override
protected void respond(final AjaxRequestTarget target) {
    final Request r = target.getPage().getRequest();
    final ViewType type = ViewType.forCode(r.getRequestParameters().getParameterValue("view").toString());
    final DateTimeFormatter fmt = ISODateTimeFormat.dateTimeParser().withZone(PFUserContext.getDateTimeZone());
    final DateMidnight start = fmt.parseDateTime(r.getRequestParameters().getParameterValue("start").toString())
            .toDateMidnight();/*from   w w  w.  j  av a  2s  .c o m*/
    final DateMidnight end = fmt.parseDateTime(r.getRequestParameters().getParameterValue("end").toString())
            .toDateMidnight();
    final DateMidnight visibleStart = fmt
            .parseDateTime(r.getRequestParameters().getParameterValue("visibleStart").toString())
            .toDateMidnight();
    final DateMidnight visibleEnd = fmt
            .parseDateTime(r.getRequestParameters().getParameterValue("visibleEnd").toString())
            .toDateMidnight();
    final View view = new View(type, start, end, visibleStart, visibleEnd);
    final CalendarResponse response = new CalendarResponse(getCalendar(), target);
    onViewDisplayed(view, response);
}

From source file:net.schweerelos.parrot.model.NodeWrapper.java

License:Open Source License

private String createToolTip(ParrotModel model) {
    if (!isOntResource()) {
        return "";
    }/*from   w w w. ja v a 2s  .  c o  m*/
    OntResource resource = getOntResource();
    if (!resource.isIndividual() || resource.isProperty()) {
        return "";
    }

    StringBuilder text = new StringBuilder();

    // use extracted model to speed up reasoning
    OntModel ontModel = model.getOntModel();
    ModelExtractor extractor = new ModelExtractor(ontModel);
    extractor.setSelector(StatementType.PROPERTY_VALUE);
    Model eModel = extractor.extractModel();

    Resource eResource = eModel.getResource(resource.getURI());

    StmtIterator props = eResource.listProperties();
    while (props.hasNext()) {
        Statement statement = props.nextStatement();
        Property pred = statement.getPredicate();
        if (!pred.isURIResource()) {
            continue;
        }
        OntProperty ontPred = ontModel.getOntProperty(pred.getURI());
        if (ontPred == null) {
            continue;
        }
        if (ParrotModelHelper.showTypeAsSecondary(ontModel, ontPred)) {
            // anything in the tooltip yet? if so, add line break
            text.append(text.length() > 0 ? "<br>" : "");
            // put in extracted predicate label
            text.append(extractLabel(ontPred));
            text.append(" ");

            RDFNode object = statement.getObject();
            if (object.isLiteral()) {
                Literal literal = (Literal) object.as(Literal.class);
                String lexicalForm = literal.getLexicalForm();
                if (literal.getDatatype().equals(XSDDatatype.XSDdateTime)) {
                    DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
                    DateTime dateTime = parser.parseDateTime(lexicalForm);
                    DateTimeFormatterBuilder formatter = new DateTimeFormatterBuilder()
                            .appendMonthOfYearShortText().appendLiteral(' ').appendDayOfMonth(1)
                            .appendLiteral(", ").appendYear(4, 4).appendLiteral(", ").appendHourOfHalfday(1)
                            .appendLiteral(':').appendMinuteOfHour(2).appendHalfdayOfDayText()
                            .appendLiteral(" (").appendTimeZoneName().appendLiteral(", UTC")
                            .appendTimeZoneOffset("", true, 1, 1).appendLiteral(')');
                    String prettyDateTime = formatter.toFormatter().print(dateTime);
                    text.append(prettyDateTime);
                } else {
                    text.append(lexicalForm);
                }
            } else if (object.isURIResource()) {
                OntResource ontObject = ontModel.getOntResource((Resource) object.as(Resource.class));
                if (ontObject == null) {
                    continue;
                }
                text.append(extractLabel(ontObject));
            }
        }
    }
    // surround with html tags
    text.insert(0, "<html>");
    text.append("</html>");

    String result = text.toString();
    if (result.equals("<html></html>")) {
        result = "";
    }
    return result;
}

From source file:net.vexelon.currencybg.app.utils.DateTimeUtils.java

License:Open Source License

/**
 *
 * @param dateTime//  www  .j  a v a 2s  .c o m
  * @return
  */
public static Date parseStringToDate(String dateTime) {
    DateTimeFormatter parse = ISODateTimeFormat.dateTimeParser();
    DateTime dateTimeHere = parse.parseDateTime(dateTime);
    Date dateNew = dateTimeHere.toDate();
    return dateNew;
}