Example usage for org.joda.time DateTime parse

List of usage examples for org.joda.time DateTime parse

Introduction

In this page you can find the example usage for org.joda.time DateTime parse.

Prototype

public static DateTime parse(String str, DateTimeFormatter formatter) 

Source Link

Document

Parses a DateTime from the specified string using a formatter.

Usage

From source file:DataConverter.java

public static Invoice[] readInvoice(Person[] persons, Customer[] customers, Product[] products) {
    try {/*from   w  ww . ja  v a2 s  .  c  om*/
        Scanner s = new Scanner(new FileReader("data/Invoices.dat"));
        int count = s.nextInt(); //Number of entries. 
        Invoice[] invoices = new Invoice[count]; //Array to hold invoices
        int iterator = 0;
        s.nextLine(); //Advance scanner to nextline
        while (s.hasNext()) {
            String inLine = s.nextLine(); //Make a string out of the next line
            String[] info;
            String[] invProducts; //Use this to handle product situation
            info = inLine.split(";"); //Create array of strings from each line, ; delimited
            //First, instantiate new invoice object
            invoices[iterator] = new Invoice(info[0]);
            for (Customer c : customers) {
                if (c.getCustomerCode().equalsIgnoreCase(info[1])) {
                    invoices[iterator].setCustomer(c);
                }
            } //End customers for each
            for (Person p : persons) {
                if (p.getPersonCode().equals(info[2])) {
                    invoices[iterator].setSalesPerson(p);
                }
            } // End persons for each

            //This is a String array of product information
            invProducts = info[3].split(",");
            for (String x : invProducts) {
                int index = x.indexOf(":"); //Get index of occurence of ":"
                String code = x.substring(0, index); //This is the product code
                for (Product p : products) { //Iterate over each product in product array
                    if (p.getCode().equals(code)) {
                        if (p.getClass().getSimpleName().equals("Equipment")) {
                            invoices[iterator].addProduct(p, Integer.parseInt(x.substring(index + 1)));
                        } else if (p.getClass().getSimpleName().equals("Consultation")) {
                            invoices[iterator].addProduct(p, Integer.parseInt(x.substring(index + 1)));
                        } else if (p.getClass().getSimpleName().equals("License")) {
                            //First we need to get the number of days
                            int index2; //PLacekeeper for substring formation
                            DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");

                            index2 = x.indexOf(":", index + 1); //Move index to next ":"

                            String start = x.substring(index + 1, index2);
                            String end = x.substring(index2 + 1);

                            DateTime begin = new DateTime(DateTime.parse(start, fmt));
                            DateTime finish = new DateTime(DateTime.parse(end, fmt));
                            int period = Days.daysBetween(begin, finish).getDays();
                            invoices[iterator].addProduct(p, period);
                        }
                    }
                } //End for each product loop
            } //End for stringx:invProducts 

            iterator++;
        } //End while
        s.close();
        return invoices;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

}

From source file:beans.utilidades.MetodosGenerales.java

public String esFecha(String f, String format) {
    /*/*  ww w  . j  a  v a 2 s.c  o m*/
     *  null=invalido ""=aceptado pero vacio "valor"=aceptado (valor para db)
     */
    if (f.trim().length() == 0) {
        return "";
    }
    try {
        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
        DateTimeFormatter fmt2 = DateTimeFormat.forPattern(format);
        DateTime the_date = DateTime.parse(f, fmt2);//trata de convertir al formato "format"(me llega por parametro)
        return fmt.print(the_date);//lo imprime en el formato "yyyy-MM-dd"
    } catch (Throwable ex) {
        return null;//invalida
    }
}

From source file:ca.farrelltonsolar.classic.PVOutputService.java

License:Apache License

public static DateTime LogDate() {
    DateTime logDate = null;//from w ww  .j  a  v a  2s .c  o  m
    ChargeController cc = MonitorApplication.chargeControllers().getCurrentChargeController();
    if (cc != null) {
        String fName = cc.getPVOutputLogFilename();
        if (fName != null && fName.length() > 0) {
            try {
                String logDateSubstring = fName.substring(18, 28);
                logDate = DateTime.parse(logDateSubstring, DateTimeFormat.forPattern("yyyy-MM-dd"));
            } catch (Exception ex) {
                Log.w("PVOutputService", String.format("LogDate parse filename failed ex: %s", ex));
            }
        }
    }

    return logDate;
}

From source file:ca.farrelltonsolar.classic.PVOutputUploader.java

License:Apache License

private boolean doUpload(ChargeController controller) throws InterruptedException, IOException {
    String uploadDateString = controller.uploadDate();
    String SID = controller.getSID();
    String fName = controller.getPVOutputLogFilename();
    if (fName != null && fName.length() > 0 && SID != null && SID.length() > 0) {
        DateTime logDate = PVOutputService.LogDate();
        int numberOfDays = Constants.PVOUTPUT_RECORD_LIMIT;
        if (uploadDateString.length() > 0) {
            DateTime uploadDate = DateTime.parse(uploadDateString, DateTimeFormat.forPattern("yyyy-MM-dd"));
            numberOfDays = Days.daysBetween(uploadDate, logDate).getDays();
        }/*w w w .  j a v a2  s. c  om*/
        numberOfDays = numberOfDays > Constants.PVOUTPUT_RECORD_LIMIT ? Constants.PVOUTPUT_RECORD_LIMIT
                : numberOfDays; // limit to 20 days as per pvOutput limits
        if (numberOfDays > 0) {
            Log.d(getClass().getName(), String.format("PVOutput uploading: %s for %d days on thread: %s", fName,
                    numberOfDays, Thread.currentThread().getName()));
            DateTime now = DateTime.now();
            String UploadDate = DateTimeFormat.forPattern("yyyy-MM-dd").print(now);
            Bundle logs = load(fName);
            float[] mData = logs.getFloatArray(String.valueOf(Constants.CLASSIC_KWHOUR_DAILY_CATEGORY)); // kWh/day
            boolean uploadDateRecorded = false;
            for (int i = 0; i < numberOfDays; i++) {
                logDate = logDate.minusDays(1); // latest log entry is for yesterday
                Socket pvOutputSocket = Connect(pvOutput);
                DataOutputStream outputStream = new DataOutputStream(
                        new BufferedOutputStream(pvOutputSocket.getOutputStream()));
                String dateStamp = DateTimeFormat.forPattern("yyyyMMdd").print(logDate);
                StringBuilder feed = new StringBuilder("GET /service/r2/addoutput.jsp");
                feed.append("?key=");
                feed.append(APIKey);
                feed.append("&sid=");
                feed.append(SID);
                feed.append("&d=");
                feed.append(dateStamp);
                feed.append("&g=");
                String wh = String.valueOf(mData[i] * 100);
                feed.append(wh);
                feed.append("\r\n");
                feed.append("Host: ");
                feed.append(pvOutput);
                feed.append("\r\n");
                feed.append("\r\n");
                String resp = feed.toString();
                outputStream.writeBytes(resp);
                outputStream.flush();
                pvOutputSocket.close();
                if (uploadDateRecorded == false) {
                    controller.setUploadDate(UploadDate);
                    uploadDateRecorded = true;
                }
                Thread.sleep(Constants.PVOUTPUT_RATE_LIMIT); // rate limit
            }
            return true;
        }
    }
    return false;
}

From source file:classes.Querys.java

private String restarDias(String fecha, Integer cantidad) throws ParseException {

    DateTime dateTime = DateTime.parse(fecha, DateTimeFormat.forPattern("dd-MM-yyyy"));

    dateTime = dateTime.minusDays(cantidad);

    return dateTime.toString("dd-MM-yyyy");

}

From source file:classes.Querys.java

private String sumarDias(String fecha, Integer cantidad) throws ParseException {

    DateTime dateTime = DateTime.parse(fecha, DateTimeFormat.forPattern("dd-MM-yyyy"));

    dateTime = dateTime.plusDays(cantidad);

    return dateTime.toString("dd-MM-yyyy");

}

From source file:cn.teamlab.wg.framework.struts2.json.interceptor.JsonExtendPopulator.java

License:Apache License

@SuppressWarnings("unchecked")
public Object convert(Class clazz, Type type, Object value, Method method)
        throws IllegalArgumentException, JSONException, IllegalAccessException, InvocationTargetException,
        InstantiationException, NoSuchMethodException, IntrospectionException {

    if (value == null) {
        // if it is a java primitive then get a default value, otherwise
        // leave it as null
        return clazz.isPrimitive() ? convertPrimitive(clazz, value, method) : null;
    } else if (isJSONPrimitive(clazz))
        return convertPrimitive(clazz, value, method);
    else if (Collection.class.isAssignableFrom(clazz))
        return convertToCollection(clazz, type, value, method);
    else if (Map.class.isAssignableFrom(clazz))
        return convertToMap(clazz, type, value, method);
    else if (clazz.isArray())
        return convertToArray(clazz, type, value, method);
    else if (value instanceof Map) {
        // nested bean
        Object convertedValue = clazz.newInstance();
        this.populateObject(convertedValue, (Map) value);
        return convertedValue;
    } else if (BigDecimal.class.equals(clazz)) {
        return new BigDecimal(value != null ? value.toString() : "0");
    } else if (BigInteger.class.equals(clazz)) {
        return new BigInteger(value != null ? value.toString() : "0");
    } else if (DateTime.class.equals(clazz)) {
        String val = value.toString();
        DateTimeFormatter format = null;
        if (Pattern.compile("^[0-9]{4}-[0-9]{1,2}-[0-9]{2}$").matcher(val).matches()) {
            format = DateTimeFormat.forPattern(DateFormatter.SDF_YMD);
        } else if (Pattern.compile("^[0-9]{4}-[0-9]{1,2}-[0-9]{2} [0-9]{2}:[0-9]{2}$").matcher(val).matches()) {
            format = DateTimeFormat.forPattern(DateFormatter.SDF_YMDHMS2);
        } else if (Pattern.compile("^[0-9]{4}-[0-9]{1,2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$").matcher(val)
                .matches()) {/*w  w w  . ja v  a  2  s . c  om*/
            format = DateTimeFormat.forPattern(DateFormatter.SDF_YMDHMS5);
        } else if (Pattern.compile("^[0-9]{4}/[0-9]{1,2}/[0-9]{2}$").matcher(val).matches()) {
            format = DateTimeFormat.forPattern(DateFormatter.SDF_YMD9);
        } else if (Pattern.compile("^[0-9]{4}/[0-9]{1,2}/[0-9]{2} [0-9]{2}:[0-9]{2}$").matcher(val).matches()) {
            format = DateTimeFormat.forPattern(DateFormatter.SDF_YMDHM2);
        } else if (Pattern.compile("^[0-9]{4}/[0-9]{1,2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$").matcher(val)
                .matches()) {
            format = DateTimeFormat.forPattern(DateFormatter.SDF_YMDHMS);
        } else if (Pattern.compile("^[0-9]{4}-[0-9]{1,2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}$")
                .matcher(val).matches()) {
            format = DateTimeFormat.forPattern(DateFormatter.SDF_YMDHMS6);
        } else {
            format = DateTimeFormat.forPattern(DateFormatter.SDF_YMD4);
        }

        return DateTime.parse(value.toString(), format);
    } else {
        throw new JSONException("Incompatible types for property " + method.getName());
    }
}

From source file:com.ace.commons.utils.TimeUtils.java

public static DateTime parse(String time) {
    DateTimeFormatter sFormat = DateTimeFormat.forPattern(DATETIME_DATE_NORMAL_FORMAT);
    DateTimeFormatter lFormat = DateTimeFormat.forPattern(DATETIME_NORMAL_FORMAT);
    //?/*from  www.j  a v  a2  s.  c  o  m*/
    if (time != null && !time.isEmpty()) {
        return time.length() > 10 ? DateTime.parse(time, lFormat) : DateTime.parse(time, sFormat);
    }
    return null;
}

From source file:com.ace.erp.utils.TimeUtils.java

public static DateTime parse(String time) {
    DateTimeFormatter sFormat = DateTimeFormat.forPattern(DATETIME_DATE_NORMAL_FORMAT);
    DateTimeFormatter lFormat = DateTimeFormat.forPattern(DATETIME_NORMAL_FORMAT);
    //?/*from  w w w . java 2  s. co  m*/
    if (!StringUtils.isNullOrEmpty(time)) {
        return time.length() > 10 ? DateTime.parse(time, lFormat) : DateTime.parse(time, sFormat);
    }
    return null;
}

From source file:com.almende.arum.EventPusher.java

License:Apache License

/**
 * Load events./*from  www . j  a v  a 2  s  . com*/
 *
 * @param filename
 *            the filename
 * @return the integer
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Access(AccessType.PUBLIC)
public Integer loadEvents(@Name("filename") String filename) throws IOException {
    final BufferedReader reader = new BufferedReader(new FileReader(filename));
    final DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");

    events.clear();

    String line = reader.readLine();
    while (line != null) {

        if (line.isEmpty()) {
            continue;
        }
        final ObjectNode event = JOM.createObjectNode();
        final String[] elements = line.split(",");
        if (!elements[0].equals("jobId")) {
            event.put("jobId", elements[0].trim());
            event.put("time", DateTime.parse(elements[1], formatter).toString());
            event.put("performedBy", elements[2].trim());
            event.put("type", elements[3].trim());
            event.put("assignment", elements[4].trim());
            event.put("productId", elements[5].trim());
            event.put("operation", elements[6].trim());

            if (elements.length > 7) {
                final String[] requirements = elements[7].split(";");
                final ArrayNode reqs = JOM.createArrayNode();
                for (String req : requirements) {
                    req = req.replaceAll("\"", "");
                    if (req.contains("(")) {
                        final ObjectNode r = JOM.createObjectNode();
                        r.put("type", req.substring(0, req.indexOf("(") - 1).trim());
                        r.put("agentId", req.substring(req.indexOf("(") + 1, req.indexOf(")")).trim());
                        reqs.add(r);
                    } else {
                        final ObjectNode r = JOM.createObjectNode();
                        r.put("type", req.trim());
                        reqs.add(r);
                    }
                }
                event.set("prerequisites", reqs);
            }
            events.add(event);
        }
        line = reader.readLine();

    }
    reader.close();
    return events.size();
}