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:gsonjodatime.DateTimeConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>/*from w  w  w.ja  v a2  s  . co  m*/
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    // Do not try to deserialize null or empty values
    if (json.getAsString() == null || json.getAsString().isEmpty()) {
        return null;
    }

    final DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    return fmt.parseDateTime(json.getAsString());
}

From source file:Implement.DAO.BookingDAOImpl.java

@Override
public void insertOfflineEngineBooking(String bookingDate, String tripDate, String tripTime, int noPackage,
        int packageID, String resourceNote, String customerName, String customerPhone, String customerEmail,
        String durationType, int duration, int smallestInterval, int providerID) {

    //  construct dynamic sql for used resources
    DateTimeFormatter formatterDateAndHour = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
    String travelTimeStr = tripDate;
    if (!durationType.equals("days")) {
        travelTimeStr += " " + tripTime + ":00";
    } else {/*  www .j  a va  2 s .  co m*/
        travelTimeStr += " 00:00:00";
    }
    DateTime travelTime = formatterDateAndHour.parseDateTime(travelTimeStr);
    DateTime endTime = new DateTime(travelTime);

    if (!durationType.equals("days")) {
        // change hours to minutes
        if (durationType.equals("hours")) {
            duration *= 60;
        }
        travelTime = travelTime.minusMinutes(duration);
        endTime = endTime.plusMinutes(duration);
    } else {
        travelTime = travelTime.minusDays(duration - 1);
        endTime = endTime.plusDays(duration + 1);
    }

    // loop each 5 minutes
    DateTimeFormatter fmtDate = DateTimeFormat.forPattern("MM/dd/YYYY");
    DateTimeFormatter fmtTime = DateTimeFormat.forPattern("HH:mm");
    String valueStr = "VALUES ";
    DateTime eachTime = new DateTime(travelTime);
    String date = fmtDate.print(eachTime);
    String time = fmtTime.print(eachTime);
    valueStr += " (@ResourceIDVar,'" + date + "','" + time + "',@NoUsedResourcesVar, @providerIDVar)";
    eachTime = eachTime.plusMinutes(smallestInterval);
    while (eachTime.isBefore(endTime)) {
        date = fmtDate.print(eachTime);
        time = fmtTime.print(eachTime);
        valueStr += ",(@ResourceIDVar,'" + date + "','" + time + "',@NoUsedResourcesVar, @providerIDVar)";
        eachTime = eachTime.plusMinutes(smallestInterval);
    }

    String insertStmt = "INSERT INTO UsedResources(ResourceID, TripDate, TripTime, NoUsedResources, ProviderID) ";
    insertStmt += valueStr;

    // Build Param Condition For Procedure
    String paramCondition = "@ResourceIDVar INT, @NoUsedResourcesVar INT, @providerIDVar INT";

    simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("InsertOfflineBooking");
    SqlParameterSource in = new MapSqlParameterSource().addValue("bookingDate", bookingDate)
            .addValue("providerID", providerID).addValue("tripDate", tripDate).addValue("tripTime", tripTime)
            .addValue("noPackage", noPackage).addValue("packageID", packageID)
            .addValue("resourceNote", resourceNote).addValue("customerName", customerName)
            .addValue("customerPhone", customerPhone).addValue("customerEmail", customerEmail)
            .addValue("InsertStatement", insertStmt).addValue("ParmDefinition", paramCondition);
    simpleJdbcCall.execute(in);
}

From source file:Implement.DAO.BookingDAOImpl.java

@Override
public void insertOfflineBooking(int providerID, int days, int hours, int minutes, long bookingTime,
        long tripTime, String dateStr, String timeStr, String customerName, String customerPhone, String email,
        List<OfflineResourceDTO> offlineResources, int smallestInterval, long resourceTime) {
    DateTimeFormatter fmtDate = DateTimeFormat.forPattern("MM/dd/YYYY");
    DateTimeFormatter fmtTime = DateTimeFormat.forPattern("HH:mm");

    //  construct dynamic sql for used resources
    DateTimeFormatter formatterDateAndHour = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
    String travelTimeStr = dateStr;
    if (days == 0) {
        travelTimeStr += " " + timeStr + ":00";
    } else {//w  w  w . j  av  a  2 s. co  m
        travelTimeStr += " 00:00:00";
    }

    // insert offline resources first
    int i = 0;
    OfflineResourceDTO offlineResource = offlineResources.get(i);
    int providerResurceID = offlineResource.getProviderResourceID();
    int resourceHours = offlineResource.getHours();
    int resourceMinutes = offlineResource.getMinutes();
    int resourceDays = offlineResource.getDays();
    int noUnits = offlineResource.getNoUnits();
    String offlineResourceValue = "VALUES ";
    offlineResourceValue += "(@offlineBookingIDVar, " + providerResurceID + "," + noUnits + "," + resourceHours
            + "," + resourceMinutes + "," + resourceDays + ")";

    String usedResourceValue = "VALUES ";
    DateTime travelTime = formatterDateAndHour.parseDateTime(travelTimeStr);
    DateTime endTime = new DateTime(travelTime);
    if (resourceDays > 0) {
        endTime = endTime.plusDays(resourceDays);
    } else {
        // change hours to minutes
        int duration = resourceHours * 60 + resourceMinutes;
        endTime = endTime.plusMinutes(duration);
    }

    // loop each 5 minutes
    DateTime eachTime = new DateTime(travelTime);
    String date = fmtDate.print(eachTime);
    String time = fmtTime.print(eachTime);
    int usedResouceMinutes = eachTime.getMinuteOfDay();

    DateTime usedResourceOnlyDate = formatterDateAndHour.parseDateTime(date + " 00:00:00");
    long usedResourceMil = usedResourceOnlyDate.getMillis();
    usedResourceValue += " (" + providerResurceID + "," + usedResourceMil + "," + usedResouceMinutes + ","
            + noUnits + ",'" + date + "','" + time + "',@bookingCodeVar,@offlineBookingIDVar)";

    eachTime = eachTime.plusMinutes(smallestInterval);
    while (eachTime.isBefore(endTime)) {
        date = fmtDate.print(eachTime);
        time = fmtTime.print(eachTime);

        usedResourceOnlyDate = formatterDateAndHour.parseDateTime(date + " 00:00:00");
        usedResourceMil = usedResourceOnlyDate.getMillis();
        usedResouceMinutes = eachTime.getMinuteOfDay();
        usedResourceValue += ",(" + providerResurceID + "," + usedResourceMil + "," + usedResouceMinutes + ","
                + noUnits + ",'" + date + "','" + time + "',@bookingCodeVar,@offlineBookingIDVar)";
        eachTime = eachTime.plusMinutes(smallestInterval);
    }

    i++;
    int resourceLength = offlineResources.size();
    for (; i < resourceLength; i++) {
        offlineResource = offlineResources.get(i);
        providerResurceID = offlineResource.getProviderResourceID();
        resourceHours = offlineResource.getHours();
        resourceMinutes = offlineResource.getMinutes();
        resourceDays = offlineResource.getDays();
        noUnits = offlineResource.getNoUnits();
        offlineResourceValue += ",(@offlineBookingIDVar, " + providerResurceID + "," + noUnits + ","
                + resourceHours + "," + resourceMinutes + "," + resourceDays + ")";

        travelTime = formatterDateAndHour.parseDateTime(travelTimeStr);
        endTime = new DateTime(travelTime);
        if (resourceDays > 0) {
            endTime = endTime.plusDays(resourceDays);
        } else {

            // change hours to minutes
            int duration = resourceHours * 60 + resourceMinutes;
            endTime = endTime.plusMinutes(duration);
        }

        // loop each 5 minutes
        eachTime = new DateTime(travelTime);
        date = fmtDate.print(eachTime);
        time = fmtTime.print(eachTime);

        usedResouceMinutes = eachTime.getMinuteOfDay();

        usedResourceOnlyDate = formatterDateAndHour.parseDateTime(date + " 00:00:00");
        usedResourceMil = usedResourceOnlyDate.getMillis();
        usedResourceValue += ",(" + providerResurceID + "," + usedResourceMil + "," + usedResouceMinutes + ","
                + noUnits + ",'" + date + "','" + time + "',@bookingCodeVar,@offlineBookingIDVar)";

        eachTime = eachTime.plusMinutes(smallestInterval);
        while (eachTime.isBefore(endTime)) {
            date = fmtDate.print(eachTime);
            time = fmtTime.print(eachTime);

            usedResourceOnlyDate = formatterDateAndHour.parseDateTime(date + " 00:00:00");
            usedResourceMil = usedResourceOnlyDate.getMillis();
            usedResouceMinutes = eachTime.getMinuteOfDay();
            usedResourceValue += ",(" + providerResurceID + "," + usedResourceMil + "," + usedResouceMinutes
                    + "," + noUnits + ",'" + date + "','" + time + "',@bookingCodeVar,@offlineBookingIDVar)";
            eachTime = eachTime.plusMinutes(smallestInterval);
        }
    }

    String resourceInsertingStmt = "INSERT INTO OfflineResource(OfflineBookingID, ProviderResourceID, NoUnits,"
            + "Hours, Minutes,Days) ";
    resourceInsertingStmt += offlineResourceValue;
    String resourceInsertingParmDefinition = "@offlineBookingIDVar INT";

    String usedResourceInsertingStmt = "INSERT INTO UsedProviderResource(ProviderResourceID, Date, Time, NoUsedResources,"
            + "DateStr,TimeStr,BookingCode,OfflineBookingID)";
    usedResourceInsertingStmt += usedResourceValue;
    String usedResourceInsertingParmDefinition = "@bookingCodeVar NVARCHAR(10)," + "@offlineBookingIDVar INT";

    simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("InsertNewOfflineBooking");
    SqlParameterSource in = new MapSqlParameterSource().addValue("days", days).addValue("minutes", minutes)
            .addValue("hours", hours).addValue("bookingTime", bookingTime).addValue("tripTime", tripTime)
            .addValue("dateStr", dateStr).addValue("timeStr", timeStr).addValue("customerName", customerName)
            .addValue("customerPhone", customerPhone).addValue("customerPhone", customerPhone)
            .addValue("email", email).addValue("providerID", providerID)
            .addValue("ResourceInsertingStmt", resourceInsertingStmt)
            .addValue("ResourceInsertingParmDefinition", resourceInsertingParmDefinition)
            .addValue("UsedResourceInsertingStmt", usedResourceInsertingStmt)
            .addValue("UsedResourceInsertingParmDefinition", usedResourceInsertingParmDefinition);
    simpleJdbcCall.execute(in);
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public void insertOfflineBooking(String data, int providerID) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");

    JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
    int hours;/*from  ww w. j  a v  a  2 s.  c o  m*/
    try {
        hours = jsonObject.get("hours").getAsInt();
    } catch (Exception e) {
        hours = 0;
    }

    int minutes;
    try {
        minutes = jsonObject.get("minutes").getAsInt();
    } catch (Exception e) {
        minutes = 0;
    }

    int days;
    try {
        days = jsonObject.get("days").getAsInt();
    } catch (Exception e) {
        days = 0;
    }

    String dateStr = jsonObject.get("dateStr").getAsString();
    // get resourceTime
    DateTime resourceTimeDT = formatter.parseDateTime(dateStr + " 00:00:00");
    long resourceTime = resourceTimeDT.getMillis();

    String customerName = jsonObject.get("customerName").getAsString();
    String customerPhone = jsonObject.get("customerPhone").getAsString();
    String email;
    try {
        email = jsonObject.get("email").getAsString();
    } catch (Exception e) {
        email = null;
    }

    JsonArray resourceJsonArray = jsonObject.get("resources").getAsJsonArray();
    List<OfflineResourceDTO> offlineResources = new ArrayList<>();
    for (JsonElement resourceJsonElement : resourceJsonArray) {
        JsonObject resourceObject = resourceJsonElement.getAsJsonObject();
        int providerResourceID = resourceObject.get("id").getAsInt();
        int noUnits = resourceObject.get("noUnits").getAsInt();
        int resourceHours = hours;
        int resourceMinutes = minutes;
        int resourceDays = days;
        //            int resourceHours = resourceObject.get("hours").getAsInt();
        //            int resourceMinutes = resourceObject.get("minutes").getAsInt();
        //            int resourceDays;
        //            try {
        //                resourceDays = resourceObject.get("days").getAsInt();
        //            } catch (Exception e) {
        //                resourceDays = 0;
        //            }
        OfflineResourceDTO newOfflineResource = new OfflineResourceDTO(providerResourceID, noUnits,
                resourceHours, resourceMinutes, resourceDays);
        offlineResources.add(newOfflineResource);
    }

    DateTime now = new DateTime();
    long bookingTime = now.getMillis();

    String timeStr;
    DateTime tripTimeOb;
    if (days > 0) {
        timeStr = null;
        tripTimeOb = formatter.parseDateTime(dateStr + " 00:00:00");
    } else {
        timeStr = jsonObject.get("timeStr").getAsString();
        tripTimeOb = formatter.parseDateTime(dateStr + " " + timeStr + ":00");
    }
    long tripTime = tripTimeOb.getMillis();

    bookingDAO.insertOfflineBooking(providerID, days, hours, minutes, bookingTime, tripTime, dateStr, timeStr,
            customerName, customerPhone, email, offlineResources, MINIMUM_INTERVAL, resourceTime);
}

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());
    }/* w w w  .  j  a  v a 2s  .c  om*/

    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.druid.timeline.DataSegmentUtils.java

License:Apache License

/**
 * Parses a segment identifier into its components: dataSource, interval, version, and any trailing tags. Ignores
 * shard spec.//from   w  ww. ja v a  2  s .com
 *
 * It is possible that this method may incorrectly parse an identifier, for example if the dataSource name in the
 * identifier contains a DateTime parseable string such as 'datasource_2000-01-01T00:00:00.000Z' and dataSource was
 * provided as 'datasource'. The desired behavior in this case would be to return null since the identifier does not
 * actually belong to the provided dataSource but a non-null result would be returned. This is an edge case that would
 * currently only affect paged select queries with a union dataSource of two similarly-named dataSources as in the
 * given example.
 *
 * @param dataSource the dataSource corresponding to this identifier
 * @param identifier segment identifier
 * @return a {@link DataSegmentUtils.SegmentIdentifierParts} object if the identifier could be parsed, null otherwise
 */
public static SegmentIdentifierParts valueOf(String dataSource, String identifier) {
    if (!identifier.startsWith(StringUtils.format("%s_", dataSource))) {
        return null;
    }

    String remaining = identifier.substring(dataSource.length() + 1);
    String[] splits = remaining.split(DataSegment.delimiter);
    if (splits.length < 3) {
        return null;
    }

    DateTimeFormatter formatter = ISODateTimeFormat.dateTime();

    try {
        DateTime start = formatter.parseDateTime(splits[0]);
        DateTime end = formatter.parseDateTime(splits[1]);
        String version = splits[2];
        String trail = splits.length > 3 ? join(splits, DataSegment.delimiter, 3, splits.length) : null;

        return new SegmentIdentifierParts(dataSource, new Interval(start.getMillis(), end.getMillis()), version,
                trail);
    } catch (IllegalArgumentException e) {
        return null;
    }
}

From source file:io.fabric8.maven.docker.util.Timestamp.java

License:Apache License

/**
 * Create a timestamp by parsing the given string representation which must be in an extended ISO 8601 Format
 * with Nanoseconds since this is the format used by Docker for logging (e.g. "2014-11-24T22:34:00.761764812Z")
 *
 * @param spec date specification to parse
 *///from  ww  w .j a  v a  2s. c o m
public Timestamp(String spec) {
    //
    Matcher matcher = TS_PATTERN.matcher(spec);
    if (!matcher.matches()) {
        throw new IllegalArgumentException("Invalid timestamp '" + spec + "' given.");
    }
    String millis = matcher.group(2);
    String rest = matcher.group(3);
    this.rest = rest != null ? Integer.parseInt(rest) : 0;
    DateTimeFormatter parser = ISODateTimeFormat.dateTime();
    date = parser.parseDateTime(matcher.group(1) + (millis != null ? "." + millis : ".000") + matcher.group(4));
}

From source file:io.freeswitch.event.ChannelHangupComplete.java

License:Apache License

/**
 * Gets the call start time. Timestamp when the call was answered (eg, SIP
 * 200 OK is received), in ISO 8601 format (YYYY-MM-DD hh:mm:ss), in the
 * local timezone (not UTC). If the call is not answered, this will be an
 * empty string./*ww  w  . j a  v a  2 s  .c  om*/
 *
 * @return DateTime value of the call start time.
 * @see DateTime
 */
public DateTime startTime() {
    DateTimeFormatter iso = ISODateTimeFormat.basicDateTimeNoMillis();
    return iso.parseDateTime(_event.eventHeaders().get("variable_start_stamp"));
}

From source file:io.freeswitch.event.ChannelHangupComplete.java

License:Apache License

/**
 * Gets the call end time. Timestamp when the call was hung up, in ISO 8601
 * format (YYYY-MM-DD hh:mm:ss), in the local timezone (not UTC).
 *
 * @return DateTime value of the call end time
 * @see DateTime/*from   w w w .  ja  v a 2  s .  c o m*/
 */
public DateTime endTime() {
    DateTimeFormatter iso = ISODateTimeFormat.basicDateTimeNoMillis();
    return iso.parseDateTime(_event.eventHeaders().get("variable_end_stamp"));
}

From source file:io.freeswitch.event.ChannelHangupComplete.java

License:Apache License

/**
 * Gets the time the call has been answered. Timestamp when the call was
 * answered (eg, SIP 200 OK is received), in ISO 8601 format (YYYY-MM-DD
 * hh:mm:ss), in the local timezone (not UTC). If the call is not answered,
 * this will be an empty string./*from  w  ww  .  j a  v a2  s.c om*/
 *
 * @return DateTime value of the answer time.
 */
public DateTime answerTime() {
    String stamp = _event.eventHeaders().get("variable_answer_stamp");
    if (StringUtils.isEmpty(stamp))
        return null;
    DateTimeFormatter iso = ISODateTimeFormat.basicDateTimeNoMillis();
    return iso.parseDateTime(stamp);
}