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:org.egov.api.controller.CitizenController.java

License:Open Source License

/**
 * This will update the profile of login user
 *
 * @param citizen - As json Object//from  w  w w  .  jav a 2  s.c om
 * @return Citizen
 */
@RequestMapping(value = ApiUrl.CITIZEN_UPDATE_PROFILE, method = RequestMethod.PUT, consumes = {
        "application/json" })
public ResponseEntity<String> updateProfile(@RequestBody final JSONObject citizen) {

    final ApiResponse res = ApiResponse.newInstance();
    try {
        final Citizen citizenUpdate = citizenService.getCitizenByUserName(citizen.get("userName").toString());
        citizenUpdate.setName(citizen.get("name").toString());
        citizenUpdate.setGender(Gender.valueOf(citizen.get("gender").toString()));
        if (citizen.get(EMAIL_ID_FIELD) != null && isNotBlank(citizen.get(EMAIL_ID_FIELD).toString())
                && citizen.get(EMAIL_ID_FIELD).toString().matches(EMAIL))
            citizenUpdate.setEmailId(citizen.get(EMAIL_ID_FIELD).toString());

        if (citizen.get(ALT_CONTACT_NUMBER_FIELD) != null
                && isNotBlank(citizen.get(ALT_CONTACT_NUMBER_FIELD).toString()))
            citizenUpdate.setAltContactNumber(citizen.get(ALT_CONTACT_NUMBER_FIELD).toString());

        final DateTimeFormatter ft = DateTimeFormat.forPattern("yyyy-MM-dd");
        final Date dt = ft.parseDateTime(citizen.get("dob").toString()).toDate();
        citizenUpdate.setDob(dt);

        if (citizen.get("pan") != null)
            citizenUpdate.setPan(citizen.get("pan").toString());

        if (citizen.get("aadhaarNumber") != null)
            citizenUpdate.setAadhaarNumber(citizen.get("aadhaarNumber").toString());

        citizenService.update(citizenUpdate);
        return res.setDataAdapter(new UserAdapter()).success(citizen, getMessage("msg.citizen.update.success"));

    } catch (final Exception e) {
        LOGGER.error(EGOV_API_ERROR, e);
        return ApiResponse.newInstance().error(getMessage(SERVER_ERROR_KEY));
    }

}

From source file:org.elasticsearch.xpack.sql.parser.ExpressionBuilder.java

License:Open Source License

@Override
public Literal visitTimestampEscapedLiteral(TimestampEscapedLiteralContext ctx) {
    String string = string(ctx.string());

    Location loc = source(ctx);//from  www  . ja v a2s . c om
    // parse yyyy-mm-dd hh:mm:ss(.f...)
    DateTime dt = null;
    try {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(ISODateTimeFormat.date())
                .appendLiteral(" ").append(ISODateTimeFormat.hourMinuteSecondFraction()).toFormatter();
        dt = formatter.parseDateTime(string);
    } catch (IllegalArgumentException ex) {
        throw new ParsingException(loc, "Invalid timestamp received; {}", ex.getMessage());
    }
    return new Literal(loc, dt, DataType.DATE);
}

From source file:org.emonocot.harvest.media.ImageMetadataExtractorImpl.java

License:Open Source License

/**
 * @param photoshopSchema/*from  w  w  w.j a  va 2  s  .c om*/
 * @param embeddedMetadata
 * @return Whether any properties has been updated
 */
private boolean addPhotoshopProperties(XMPSchemaPhotoshop photoshopSchema, Image embeddedMetadata,
        Image image) {
    boolean isSomethingDifferent = false;
    StringBuffer newSpatial = new StringBuffer();
    if (StringUtils.isNotBlank(embeddedMetadata.getSpatial())) {
        newSpatial.append(embeddedMetadata.getSpatial());
    }
    if (StringUtils.isNotBlank(photoshopSchema.getState())) {
        if (newSpatial.length() > 0) {
            newSpatial.append(", ");
        }
        newSpatial.append(sanitizer.sanitize(photoshopSchema.getState()));
    }
    if (StringUtils.isNotBlank(photoshopSchema.getCountry())) {
        if (newSpatial.length() > 0) {
            newSpatial.append(", ");
        }
        newSpatial.append(sanitizer.sanitize(photoshopSchema.getCountry()));
    }
    if (!newSpatial.toString().equals(embeddedMetadata.getSpatial())) {
        embeddedMetadata.setSpatial(newSpatial.toString());
        isSomethingDifferent = true;
    }
    if (StringUtils.isNotBlank(photoshopSchema.getInstructions())) {
        //N.B. We could try and use the taxon matcher to associate an additional taxon (or multiple taxa if we are clear about the separator)
        logger.info("Photoshop instruction found: " + photoshopSchema.getInstructions());
        //TODO Match Taxon?
    }
    if (embeddedMetadata.getCreated() == null && photoshopSchema.getDateCreated() != null) {
        IllegalArgumentException iae = null;
        DateTime dateCreated = null;
        for (DateTimeFormatter dateTimeFormatter : dateTimeFormatters) {
            try {
                dateCreated = dateTimeFormatter.parseDateTime(photoshopSchema.getDateCreated());

            } catch (IllegalArgumentException e) {
                iae = e;
            }
        }
        if (dateCreated == null) {
            imageAnnotator.annotate(image, AnnotationType.Warn, AnnotationCode.BadField,
                    photoshopSchema.getDateCreated() + " is not a well-formed date");
            logger.warn("Unable to set the Date Created for image" + embeddedMetadata.getId() + " identifier: "
                    + embeddedMetadata.getIdentifier(), iae);
        } else {
            embeddedMetadata.setCreated(dateCreated);
        }
    }
    return isSomethingDifferent;
}

From source file:org.eobjects.analyzer.beans.convert.ConvertToDateTransformer.java

License:Open Source License

protected Date convertFromString(final String value) {
    if ("now()".equalsIgnoreCase(value)) {
        return new NowDate();
    }/* w w  w.j  a  va2  s  .  c o m*/
    if ("today()".equalsIgnoreCase(value)) {
        return new TodayDate();
    }
    if ("yesterday()".equalsIgnoreCase(value)) {
        return new YesterdayDate();
    }

    for (DateTimeFormatter formatter : _dateTimeFormatters) {
        try {
            return formatter.parseDateTime(value).toDate();
        } catch (Exception e) {
            // proceed to next formatter
        }
    }

    try {
        long longValue = Long.parseLong(value);
        return convertFromNumber(longValue, false);
    } catch (NumberFormatException e) {
        // do nothing, proceed to dateFormat parsing
    }

    // try also with SimpleDateFormat since it is more fault tolerant in
    // millisecond parsing
    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
    try {
        return format.parse(value);
    } catch (ParseException e) {
        // do nothing
    }

    return null;
}

From source file:org.eobjects.analyzer.beans.convert.ConvertToDateTransformer.java

License:Open Source License

protected Date convertFromNumber(Number value, boolean tryDateTimeFormatters) {
    Number numberValue = (Number) value;
    long longValue = numberValue.longValue();

    String stringValue = Long.toString(longValue);

    if (tryDateTimeFormatters) {
        for (int i = 0; i < _dateTimeFormatters.length; i++) {
            String dateMask = dateMasks[i];
            boolean isPotentialNumberDateMask = dateMask.indexOf("-") == -1 && dateMask.indexOf(".") == -1
                    && dateMask.indexOf("/") == -1;
            if (isPotentialNumberDateMask) {
                DateTimeFormatter formatter = _dateTimeFormatters[i];
                try {
                    return formatter.parseDateTime(stringValue).toDate();
                } catch (Exception e) {
                    // proceed to next formatter
                }/*from www.j a v a  2 s.  c o  m*/
            }
        }
    }

    // test if the number is actually a format of the type yyyyMMdd
    if (stringValue.length() == 8 && (stringValue.startsWith("1") || stringValue.startsWith("2"))) {
        try {
            return NUMBER_BASED_DATE_FORMAT_LONG.parseDateTime(stringValue).toDate();
        } catch (Exception e) {
            // do nothing, proceed to next method of conversion
        }
    }

    // test if the number is actually a format of the type yyMMdd
    if (stringValue.length() == 6) {
        try {
            return NUMBER_BASED_DATE_FORMAT_SHORT.parseDateTime(stringValue).toDate();
        } catch (Exception e) {
            // do nothing, proceed to next method of conversion
        }
    }

    if (longValue > 5000000) {
        // this number is most probably amount of milliseconds since
        // 1970
        return new Date(longValue);
    } else {
        // this number is most probably the amount of days since
        // 1970
        return new Date(longValue * 1000 * 60 * 60 * 24);
    }
}

From source file:org.epics.archiverappliance.common.TimeUtils.java

public static java.sql.Timestamp convertFromISO8601String(String tsstr) {
    // Sample ISO8601 string 2011-02-01T08:00:00.000Z
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    DateTime dt = fmt.parseDateTime(tsstr);
    Timestamp ts = new Timestamp(dt.getMillis());
    return ts;//from ww w  .  j  a v  a  2 s. co  m
}

From source file:org.epics.archiverappliance.common.TimeUtils.java

public static java.sql.Timestamp convertFromDateTimeStringWithOffset(String tsstr) {
    // Sample string 2012-11-03T00:00:00-07:00
    DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ssZ").withOffsetParsed();
    DateTime dt = fmt.parseDateTime(tsstr);
    Timestamp ts = new Timestamp(dt.getMillis());
    return ts;// w w  w  . j  av a  2  s .com
}

From source file:org.fao.geonet.domain.ISODate.java

License:Open Source License

public static String parseISODateTimes(String input1, String input2) {
    DateTimeFormatter dto = ISODateTimeFormat.dateTime();
    PeriodFormatter p = ISOPeriodFormat.standard();
    DateTime odt1;/*from   ww  w.  ja  v a2s .c o m*/
    String odt = "";

    // input1 should be some sort of ISO time
    // eg. basic: 20080909, full: 2008-09-09T12:21:00 etc
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        DateTime idt = parseBasicOrFullDateTime(input1);
        odt1 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
        odt = odt1.toString();

    } catch (Exception e) {
        Log.error("geonetwork.domain", "Error parsing ISO DateTimes, error: " + e.getMessage(), e);
        return DEFAULT_DATE_TIME;
    }

    if (input2 == null || input2.equals(""))
        return odt;

    // input2 can be an ISO time as for input1 but also an ISO time period
    // eg. -P3D or P3D - if an ISO time period then it must be added to the
    // DateTime generated for input1 (odt1)
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        boolean minus = false;
        if (input2.startsWith("-P")) {
            input2 = input2.substring(1);
            minus = true;
        }

        if (input2.startsWith("P")) {
            Period ip = p.parsePeriod(input2);
            DateTime odt2;
            if (!minus)
                odt2 = odt1.plus(ip.toStandardDuration().getMillis());
            else
                odt2 = odt1.minus(ip.toStandardDuration().getMillis());
            odt = odt + "|" + odt2.toString();
        } else {
            DateTime idt = parseBasicOrFullDateTime(input2);
            DateTime odt2 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
            odt = odt + "|" + odt2.toString();
        }
    } catch (Exception e) {
        Log.error("geonetwork.domain", "Error parsing ISO DateTimes, error: " + e.getMessage(), e);
        return odt + "|" + DEFAULT_DATE_TIME;
    }

    return odt;
}

From source file:org.fao.geonet.domain.ISODate.java

License:Open Source License

public static DateTime parseBasicOrFullDateTime(String input1) throws Exception {
    DateTimeFormatter bd = ISODateTimeFormat.basicDate();
    DateTimeFormatter bt = ISODateTimeFormat.basicTime();
    DateTimeFormatter bdt = ISODateTimeFormat.basicDateTime();
    DateTimeFormatter dtp = ISODateTimeFormat.dateTimeParser();
    DateTime idt;//from   w w w  .jav a  2 s  .  co m
    Matcher matcher;
    if (input1.length() == 8 && !input1.startsWith("T")) {
        idt = bd.parseDateTime(input1);
    } else if (input1.startsWith("T") && !input1.contains(":")) {
        idt = bt.parseDateTime(input1);
    } else if (input1.contains("T") && !input1.contains(":") && !input1.contains("-")) {
        idt = bdt.parseDateTime(input1);
    } else if ((matcher = gsYearMonth.matcher(input1)).matches()) {
        String year = matcher.group(1);
        String month = matcher.group(2);
        String minute = "00";
        String hour = "00";
        String timezone = "Z";
        if (matcher.group(4) != null) {
            minute = matcher.group(5);
            hour = matcher.group(4);
            timezone = matcher.group(6);
        }

        idt = generateDate(year, month, minute, hour, timezone);
    } else if ((matcher = gsYear.matcher(input1)).matches()) {
        String year = matcher.group(1);
        String month = "01";
        String minute = "00";
        String hour = "00";
        String timezone = "Z";
        if (matcher.group(3) != null) {
            minute = matcher.group(4);
            hour = matcher.group(3);
            timezone = matcher.group(5);
        }

        idt = generateDate(year, month, minute, hour, timezone);
    } else if ((matcher = htmlFormat.matcher(input1)).matches()) {
        // Fri Jan 01 2010 00:00:00 GMT+0100 (CET)
        String month = matcher.group(2);
        switch (month) {
        case "Jan":
            month = "1";
            break;
        case "Feb":
            month = "2";
            break;
        case "Mar":
            month = "3";
            break;
        case "Apr":
            month = "4";
            break;
        case "May":
            month = "5";
            break;
        case "Jun":
            month = "6";
            break;
        case "Jul":
            month = "7";
            break;
        case "Aug":
            month = "8";
            break;
        case "Sep":
            month = "9";
            break;
        case "Oct":
            month = "10";
            break;
        case "Nov":
            month = "11";
            break;
        default:
            month = "12";
            break;
        }
        String day = matcher.group(3);
        String year = matcher.group(4);
        String hour = matcher.group(5);
        String minute = matcher.group(6);
        String second = matcher.group(7);
        String timezone = matcher.group(8);

        idt = generateDate(year, month, day, second, minute, hour, timezone);
    } else {
        idt = dtp.parseDateTime(input1);
    }
    return idt;
}

From source file:org.fao.geonet.util.JODAISODate.java

License:Open Source License

public static String parseISODateTimes(String input1, String input2) {
    DateTimeFormatter dto = ISODateTimeFormat.dateTime();
    PeriodFormatter p = ISOPeriodFormat.standard();
    DateTime odt1;/*from   w  w w  . j ava 2  s  .  c om*/
    String odt = "";

    // input1 should be some sort of ISO time 
    // eg. basic: 20080909, full: 2008-09-09T12:21:00 etc
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        DateTime idt = parseBasicOrFullDateTime(input1);
        odt1 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
        odt = odt1.toString();

    } catch (Exception e) {
        e.printStackTrace();
        return dt;
    }

    if (input2 == null || input2.equals(""))
        return odt;

    // input2 can be an ISO time as for input1 but also an ISO time period
    // eg. -P3D or P3D - if an ISO time period then it must be added to the
    // DateTime generated for input1 (odt1)
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        boolean minus = false;
        if (input2.startsWith("-P")) {
            input2 = input2.substring(1);
            minus = true;
        }

        if (input2.startsWith("P")) {
            Period ip = p.parsePeriod(input2);
            DateTime odt2;
            if (!minus)
                odt2 = odt1.plus(ip.toStandardDuration().getMillis());
            else
                odt2 = odt1.minus(ip.toStandardDuration().getMillis());
            odt = odt + "|" + odt2.toString();
        } else {
            DateTime idt = parseBasicOrFullDateTime(input2);
            DateTime odt2 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
            odt = odt + "|" + odt2.toString();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return odt + "|" + dt;
    }

    return odt;
}