Example usage for org.joda.time DateTime DateTime

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

Introduction

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

Prototype

public DateTime(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:UpdateTransaction.java

private int getDaysDiff(java.util.Date startdate, java.util.Date enddate) {
    DateTime start = new DateTime(startdate);
    DateTime end = new DateTime(enddate);

    int days = Days.daysBetween(start, end).getDays();
    return days;/*from  ww w . j  a  v a2  s  .  co  m*/

}

From source file:SOEFinalAlertBolt.java

License:Open Source License

public void execute(Tuple tuple) {

    String message = tuple.getStringByField("message");
    long timeStamp = tuple.getLongByField("timeStamp");

    LOG.info("!!Something Happened in " + nodeID);
    LOG.info("!!At : " + new DateTime(timeStamp).toString());
    LOG.info("!!Current Time : " + DateTime.now());

    try {//  w  ww.j  a  v  a2 s .c  om
        ProcessBuilder builder = new ProcessBuilder("python", PythonFILE1);
        builder.directory(new File(PythonLOCATION));
        Process process = builder.start();
        //      process.waitFor();

        //      builder = new ProcessBuilder("python", PythonFILE2);
        //      builder.directory(new File(PythonLOCATION));
        //      process = builder.start();
        //      process.waitFor();

    } catch (Exception e) {
        LOG.info("[Final Alert]\n" + e.getMessage());
    }

    _collector.ack(tuple);
}

From source file:JodaDT.java

License:Open Source License

/**
 * Creates a DateTime object from the milliseconds attribute of another
 * DateTime object. It's a kind of cloner.
 *
 * @param dateTime a DateTime object// ww w. j  a va2s.  co m
 * @return a DateTime object
 */
public static DateTime rebuild(DateTime dateTime) {
    if (dateTime != null) {
        long milis = dateTime.getMillis();
        DateTime dateTime2 = new DateTime(milis);
        return new DateTime(dateTime2);
    } else {
        return null;
    }

}

From source file:DataConverter.java

public static Invoice[] readInvoice(Person[] persons, Customer[] customers, Product[] products) {
    try {/* w  ww  .  j  a va  2  s.  co  m*/
        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:AdminLogCreator.java

public void processForExecutions(String testName, File logDir)
        throws SAXException, ParserConfigurationException, IOException {
    setTestName(testName);/*from   ww w .  ja  v a 2 s .c om*/
    String[] rootDirs = logDir.list();
    if (null != rootDirs && 0 < rootDirs.length) {
        Arrays.sort(rootDirs);
        for (int i = 0; i < rootDirs.length; i++) {
            String[] dirs = new File(logDir, rootDirs[i]).list();
            if (null != dirs && 0 < dirs.length) {
                Arrays.sort(dirs);
                for (int j = 0; j < dirs.length; j++) {
                    if (new File(new File(new File(logDir, rootDirs[i]), dirs[j]), "session.xml").exists()) {
                        File sessionFile = new File(new File(new File(logDir, rootDirs[i]), dirs[j]),
                                "session.xml");
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        dbf.setNamespaceAware(true);
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        Document doc = db.parse(sessionFile);
                        Element session = (Element) (doc.getElementsByTagName("session").item(0));
                        if ((session.getAttribute("sourcesId")).contains(testName)) {
                            Path file = sessionFile.toPath();
                            BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
                            DateTime fileCreationTime = new DateTime(attr.creationTime().toString());
                            DateTime currentTime = DateTime.now();
                            int countDay = Days.daysBetween(fileCreationTime, currentTime).getDays();
                            if (countDay <= 30) {
                                setCountLastMonth();
                                setCountLast3Month();
                                setCountLastYear();
                                setCountAllTime();
                            } else if (countDay > 30 && countDay <= 90) {
                                setCountLast3Month();
                                setCountLastYear();
                                setCountAllTime();
                            } else if (countDay > 90 && countDay <= 365) {
                                setCountLastYear();
                                setCountAllTime();
                            } else {
                                setCountAllTime();
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:AdminLogCreator.java

public void processForUsers(String testName, File logDir)
        throws SAXException, ParserConfigurationException, IOException {
    setTestName(testName);/*w ww.j  av a 2 s  .  co m*/
    String[] rootDirs = logDir.list();
    if (null != rootDirs && 0 < rootDirs.length) {
        Arrays.sort(rootDirs);
        for (int i = 0; i < rootDirs.length; i++) {
            innercountLastMonth = 0;
            innercountLast3Month = 0;
            innercountLastYear = 0;
            innercountAllTime = 0;
            String[] dirs = new File(logDir, rootDirs[i]).list();
            if (null != dirs && 0 < dirs.length) {
                Arrays.sort(dirs);
                for (int j = 0; j < dirs.length; j++) {
                    if (new File(new File(new File(logDir, rootDirs[i]), dirs[j]), "session.xml").exists()) {
                        File sessionFile = new File(new File(new File(logDir, rootDirs[i]), dirs[j]),
                                "session.xml");
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        dbf.setNamespaceAware(true);
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        Document doc = db.parse(sessionFile);
                        Element session = (Element) (doc.getElementsByTagName("session").item(0));
                        if ((session.getAttribute("sourcesId")).contains(testName)) {
                            Path file = sessionFile.toPath();
                            BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
                            DateTime fileCreationTime = new DateTime(attr.creationTime().toString());
                            DateTime currentTime = DateTime.now();
                            int countDay = Days.daysBetween(fileCreationTime, currentTime).getDays();
                            if (countDay <= 30) {
                                innercountLastMonth = 1;
                            } else if (countDay > 30 && countDay <= 90) {
                                innercountLast3Month = 1;
                            } else if (countDay > 90 && countDay <= 365) {
                                innercountLastYear = 1;
                            } else {
                                innercountAllTime = 1;
                            }
                        }
                    }
                }
            }
            if (innercountLastMonth == 1) {
                setCountLastMonth();
                setCountLast3Month();
                setCountLastYear();
                setCountAllTime();
            } else if (innercountLast3Month == 1) {
                setCountLast3Month();
                setCountLastYear();
                setCountAllTime();
            } else if (innercountLastYear == 1) {
                setCountLastYear();
                setCountAllTime();
            } else if (innercountAllTime == 1) {
                setCountAllTime();
            }
        }
    }
}

From source file:DDTDate.java

License:Apache License

/**
 * This function will populate the varsMap with new copies of values related to display format of date & time stamps.
 * Those values are based on the class (static) date variable that is currently in use.
 * Those values can later be used in verification of UI elements that are date-originated but may change in time (say, today's date, month, year - etc.)
 * The base date that is used is Locale dependent (currently, the local is assumed to be that of the workstation running the software.)
 * When relevant, values are provided in various styles (SHORT, MEDIUM, LONG, FULL) - not all date elements have all those versions available.
 * The purpose of this 'exercise' is to set up the facility for the user to verify any component of date / time stamps independently of one another or 'traditional' formatting.
 *
 * The variables maintained here are formatted with a prefix to distinguish them from other, user defined variables.
 *
 * @TODO: enable Locale modifications (at present the test machine's locale is considered and within a test session only one locale can be tested)
 *        WikiPedia: https://en.wikipedia.org/wiki/Date_format_by_country
 *        Stack Overflow (coes) http://stackoverflow.com/questions/3191664/list-of-all-locales-and-their-short-codes
 * @param varsMap//from  ww w .  j ava2 s  .com
 */
private void maintainDateProperties(Hashtable<String, Object> varsMap) throws Exception {

    String prefix = "$";

    try {
        // Build formatting objects for each of the output styles
        DateFormat shortStyleFormatter = DateFormat.getDateInstance(DateFormat.SHORT, getLocale());
        DateFormat mediumStyleFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, getLocale());
        DateFormat longStyleFormatter = DateFormat.getDateInstance(DateFormat.LONG, getLocale());
        DateFormat fullStyleFormatter = DateFormat.getDateInstance(DateFormat.FULL, getLocale());

        // Use a dedicated variable to hold values of formatting results to facilitate debugging
        // @TODO (maybe) when done debugging - convert to inline calls to maintainDateProperty ...
        String formatValue;

        // Examples reflect time around midnight of February 6 2014 - actual values DO NOT include quotes (added here for readability)

        MutableDateTime theReferenceDate = getReferenceDate(); //getReferenceDateAdjustedForTimeZone();
        // Default Date using DDTSettings pattern.
        formatValue = new SimpleDateFormat(defaultDateFormat()).format(theReferenceDate.toDate());
        maintainDateProperty(prefix + "defaultDate", formatValue, varsMap);

        // Short Date - '2/6/14'
        formatValue = shortStyleFormatter.format(theReferenceDate.toDate());
        maintainDateProperty(prefix + "shortDate", formatValue, varsMap);

        // Medium Date - 'Feb 6, 2014'
        formatValue = mediumStyleFormatter.format(theReferenceDate.toDate());
        maintainDateProperty(prefix + "mediumDate", formatValue, varsMap);

        // Long Date - 'February 6, 2014'
        formatValue = longStyleFormatter.format(theReferenceDate.toDate());
        maintainDateProperty(prefix + "longDate", formatValue, varsMap);

        // Full Date 'Thursday, February 6, 2014'
        formatValue = fullStyleFormatter.format(theReferenceDate.toDate());
        maintainDateProperty(prefix + "fullDate", formatValue, varsMap);

        // hours : minutes : seconds : milliseconds (broken to separate components)  -
        formatValue = theReferenceDate.toString("hh:mm:ss:SSS");
        if (formatValue.toString().contains(":")) {
            String[] hms = split(formatValue.toString(), ":");
            if (hms.length > 3) {
                // Hours - '12'
                formatValue = hms[0];
                maintainDateProperty(prefix + "hours", formatValue, varsMap);
                // Minutes - '02'
                formatValue = hms[1];
                maintainDateProperty(prefix + "minutes", formatValue, varsMap);
                // Seconds - '08'
                formatValue = hms[2];
                maintainDateProperty(prefix + "seconds", formatValue, varsMap);
                // Milliseconds - '324'
                formatValue = hms[3];
                maintainDateProperty(prefix + "milliseconds", formatValue, varsMap);
                // Hours in 24 hours format - '23'
                formatValue = theReferenceDate.toString("HH");
                maintainDateProperty(prefix + "hours24", formatValue, varsMap);
            } else
                setException("Failed to format reference date to four time units!");
        } else {
            setException("Failed to format reference date to its time units!");
        }

        // hours : minutes : seconds (default timestamp)  - '12:34:56'
        formatValue = theReferenceDate.toString("hh:mm:ss");
        maintainDateProperty(prefix + "timeStamp", formatValue, varsMap);

        // Short Year - '14'
        formatValue = theReferenceDate.toString("yy");
        maintainDateProperty(prefix + "shortYear", formatValue, varsMap);

        // Long Year - '2014'
        formatValue = theReferenceDate.toString("yyyy");
        maintainDateProperty(prefix + "longYear", formatValue, varsMap);

        // Short Month - '2'
        formatValue = theReferenceDate.toString("M");
        maintainDateProperty(prefix + "shortMonth", formatValue, varsMap);

        // Padded Month - '02'
        formatValue = theReferenceDate.toString("MM");
        maintainDateProperty(prefix + "paddedMonth", formatValue, varsMap);

        // Short Month Name - 'Feb'
        formatValue = theReferenceDate.toString("MMM");
        maintainDateProperty(prefix + "shortMonthName", formatValue, varsMap);

        // Long Month Name - 'February'
        formatValue = theReferenceDate.toString("MMMM");
        maintainDateProperty(prefix + "longMonthName", formatValue, varsMap);

        // Week in Year - '2014' (the year in which this week falls)
        formatValue = String.valueOf(theReferenceDate.getWeekyear());
        maintainDateProperty(prefix + "weekYear", formatValue, varsMap);

        // Short Day in date stamp - '6'
        formatValue = theReferenceDate.toString("d");
        maintainDateProperty(prefix + "shortDay", formatValue, varsMap);

        // Padded Day in date stamp - possibly with leading 0 - '06'
        formatValue = theReferenceDate.toString("dd");
        maintainDateProperty(prefix + "paddedDay", formatValue, varsMap);

        // Day of Year - '37'
        formatValue = theReferenceDate.toString("D");
        maintainDateProperty(prefix + "yearDay", formatValue, varsMap);

        // Short Day Name - 'Thu'
        formatValue = theReferenceDate.toString("E");
        maintainDateProperty(prefix + "shortDayName", formatValue, varsMap);

        // Long Day Name - 'Thursday'
        DateTime dt = new DateTime(theReferenceDate.toDate());
        DateTime.Property dowDTP = dt.dayOfWeek();
        formatValue = dowDTP.getAsText();
        maintainDateProperty(prefix + "longDayName", formatValue, varsMap);

        // AM/PM - 'AM'
        formatValue = theReferenceDate.toString("a");
        maintainDateProperty(prefix + "ampm", formatValue, varsMap);

        // Era - (BC/AD)
        formatValue = theReferenceDate.toString("G");
        maintainDateProperty(prefix + "era", formatValue, varsMap);

        // Time Zone - 'EST'
        formatValue = theReferenceDate.toString("zzz");
        maintainDateProperty(prefix + "zone", formatValue, varsMap);

        addComment(
                "Date variables replenished for date: " + fullStyleFormatter.format(theReferenceDate.toDate()));
        addComment(theReferenceDate.toString());
        System.out.println(getComments());
    } catch (Exception e) {
        setException(e);
    }
}

From source file:DDTDate.java

License:Apache License

/**
 * Creates the output the user indicated in the input (outputType component) subject to the requested style (outputStyle) component
 * @return/* w ww .  j a  v  a2  s. c om*/
 */
private String createOutput() {
    String result = "";
    try {
        // If needed, adjust the reference date by the number and type of units specified  - as per the time zone
        if (getUnits() != 0) {
            //setReferenceDate(getReferenceDateAdjustedForTimeZone());
            getReferenceDate().add(getDurationType(), getUnits());
        }

        // Create date formatters to be used for all varieties - the corresponding date variables are always set for convenience purposes
        DateFormat shortFormatter = DateFormat.getDateInstance(DateFormat.SHORT);
        DateFormat mediumFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM);
        DateFormat longFormatter = DateFormat.getDateInstance(DateFormat.LONG);
        DateFormat fullFormatter = DateFormat.getDateInstance(DateFormat.FULL);

        // Build the specific formatter specified
        DateFormat formatter = null;
        switch (getOutputStyle().toLowerCase()) {
        case "medium": {
            formatter = mediumFormatter;
            break;
        }
        case "long": {
            formatter = longFormatter;
            break;
        }
        case "full": {
            formatter = fullFormatter;
            break;
        }
        default:
            formatter = shortFormatter;
        } // output style switch

        // construct the specified result - one at a time
        MutableDateTime theReferenceDate = getReferenceDate(); //getReferenceDateAdjustedForTimeZone();
        switch (getOutputType().toLowerCase()) {
        case "date": {
            result = formatter.format(theReferenceDate.toDate());
            break;
        }

        case "time": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("hh:mm:ss");
                break;
            }
            default:
                result = theReferenceDate.toString("hh:mm:ss.SSS");
            }
            break;
        }
        // separate time components
        case "hour":
        case "minute":
        case "second":
        case "hour24": {
            String tmp = theReferenceDate.toString("hh:mm:ss");
            if (tmp.toString().contains(":")) {
                String[] hms = split(tmp.toString(), ":");
                if (hms.length > 2) {
                    switch (getOutputType().toLowerCase()) {
                    case "hour": {
                        // Hour - '12'
                        result = hms[0];
                        break;
                    }
                    case "minute": {
                        // Minutes - '34'
                        result = hms[1];
                        break;
                    }
                    case "second": {
                        // Second - '56'
                        result = hms[2];
                        break;
                    }
                    case "hour24": {
                        // Hour - '23'
                        result = theReferenceDate.toString("HH");
                        break;
                    }
                    default:
                        result = hms[0];
                    } // switch for individual time component
                } // three parts of time components
            } // timestamp contains separator ":"
            break;
        } // Hours, Minutes, Seconds

        case "year": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("yy");
                break;
            }
            default:
                result = theReferenceDate.toString("yyyy");
            }
            break;
        }

        case "month": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("M");
                break;
            }
            case "medium": {
                // padded with 0
                result = theReferenceDate.toString("MM");
                break;
            }
            case "long": {
                // short name 'Feb'
                result = theReferenceDate.toString("MMM");
                break;
            }
            default:
                // Full name 'September'
                result = theReferenceDate.toString("MMMM");
            }
            break;
        }

        case "day": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("d");
                break;
            }
            case "medium": {
                result = theReferenceDate.toString("dd");
                break;
            }
            default:
                result = theReferenceDate.toString("dd");
            }
        }

        case "doy": {
            result = theReferenceDate.toString("D");
            break;
        }

        case "dow": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("E");
                break;
            }
            case "medium": {
                DateTime dt = new DateTime(theReferenceDate.toDate());
                DateTime.Property dowDTP = dt.dayOfWeek();
                result = dowDTP.getAsText();
                break;
            }
            default:
                result = theReferenceDate.toString("E");
            }
            break;
        } // day of week

        case "zone": {
            result = theReferenceDate.toString("zzz");
            break;
        }

        case "era": {
            result = theReferenceDate.toString("G");
            break;
        }

        case "ampm": {
            result = theReferenceDate.toString("a");
            break;
        }

        default: {
            setException("Invalid Output Unit - cannot set output");
        }

        // Create full date variables for the short, medium, long, full styles

        } // output type switch
    } // try constructing result
    catch (Exception e) {
        setException(e);
    } finally {
        return result;
    }
}

From source file:DateTimeTypeAdapter.java

License:Apache License

@Override
public DateTime read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();/*from   www.ja  va2  s . co  m*/
        return null;
    }
    return new DateTime(in.nextString());
}

From source file:$.MessageReportServiceImpl.java

License:Apache License

@Override
    public List<MessageReportDto> getMessageStateSummary(Date startDate, Date endDate) {
        Assert.notNull(startDate, "startDate mustn't be null");
        Assert.notNull(endDate, "startDate mustn't be null");

        // adjust dates to start from 0.00 and end 23.59
        DateTime from = new DateTime(startDate).withTimeAtStartOfDay();
        DateTime to = new DateTime(endDate).plusDays(1).withTimeAtStartOfDay();

        return dao.getMessageStateSummary(from.toDate(), to.toDate());
    }/* w w  w  .  j  ava2 s .c o  m*/