Example usage for org.joda.time MutableDateTime getMillis

List of usage examples for org.joda.time MutableDateTime getMillis

Introduction

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

Prototype

public long getMillis() 

Source Link

Document

Gets the milliseconds of the datetime instant from the Java epoch of 1970-01-01T00:00:00Z.

Usage

From source file:ke.co.tawi.babblesms.server.session.SessionStatisticsFactory.java

License:Open Source License

/**
 *
 * @param accountUuid//  w ww.  j a  v a 2s  .c o m
 * @return session statistics
 */
public static SessionStatistics getSessionStatistics(String accountUuid) {
    int count;
    //int[] arraycount = new int[2];

    SessionStatistics stats = new SessionStatistics();

    // Get the list of all networks
    List<Network> networkList = networkDAO.getAllNetworks();
    ;

    //set the count of all incoming SMS
    stats.setAllIncomingSMSCount(countUtils.getIncomingCount(accountUuid));

    //set the count of all outgoing SMS
    stats.setAllOutgoingSMSCount(countUtils.getOutgoingLog(accountUuid));

    //set the count of all outgoing Group SMS
    //stats.setAllOutgoingSMSCount(countUtils.getOutgoingGroupLog(accountUuid));

    // Set up data for the pie charts
    for (Network network : networkList) {
        //get the count of incoming SMS according to the account and network
        count = countUtils.getIncomingCount(accountUuid, network);

        //if count is greater than zero, add the information
        if (count > 0) {
            stats.addNetworkIncomingCount(network, count);
        }

        //get the count of outgoing SMS according to the account and network
        count = countUtils.getOutgoingCount(accountUuid, network);

        //if count is greater than zero, add the information
        if (count > 0) {
            stats.addNetworkOutgoingSMSCount(network, count);
        }
    }

    // Set up data for the bar charts
    DateTime dateMidnightStart = DateTime.now().minus(Hours.hours(24 * (IncomingBarDay.DAY_COUNT)));
    DateTime dateMidnightEnd = dateMidnightStart.plus(Hours.hours(24));
    int numDays = 0;
    do {
        for (Network network : networkList) {

            //get the daily count for incoming
            count = countUtils.getIncomingCount(accountUuid, network, new Date(dateMidnightStart.getMillis()),
                    new Date(dateMidnightEnd.getMillis()));
            if (count > 0) {
                stats.addNetworkIncomingUSSDCountDay(
                        new SimpleDateFormat("MMM d").format(new Date(dateMidnightStart.getMillis())), network,
                        count);
            }
            //get the daily count for outgoing
            count = countUtils.getOutgoingCount(accountUuid, network, new Date(dateMidnightStart.getMillis()),
                    new Date(dateMidnightEnd.getMillis()));

            if (count > 0) {
                stats.addNetworkOutgoingUSSDCountDay(
                        new SimpleDateFormat("MMM d").format(new Date(dateMidnightStart.getMillis())), network,
                        count);
            }

        }
        dateMidnightStart = dateMidnightStart.plus(Hours.hours(24));
        dateMidnightEnd = dateMidnightEnd.plus(Hours.hours(24));
        numDays++;
    } while (numDays < IncomingBarDay.DAY_COUNT);

    // Set up data for the Weekly bar charts                
    int numWeeks = 0;
    MutableDateTime startwkMutableDateTime = new MutableDateTime();
    MutableDateTime endwkMutableDateTime;
    startwkMutableDateTime.setDayOfWeek(1); //get the first day of the week
    startwkMutableDateTime.setMillisOfDay(0); //get 00:00:00 time of the day

    //go back to 7 weeks
    startwkMutableDateTime.addWeeks(-7);

    do {
        // set the end date by creating a copy
        endwkMutableDateTime = new MutableDateTime(startwkMutableDateTime);
        //push it by one week
        endwkMutableDateTime.addWeeks(1);

        for (Network network : networkList) {

            //get the Weekly count for Incoming USSD
            count = countUtils.getIncomingCount(accountUuid, network,
                    new Date(startwkMutableDateTime.toDate().getTime()),
                    new Date(endwkMutableDateTime.toDate().getTime()));

            if (count > 0) {
                stats.addNetworkIncomingUSSDCountWeek(
                        new SimpleDateFormat("MMM d").format(new Date(startwkMutableDateTime.getMillis())),
                        network, count);
            }

            //get the Weekly count for Outgoing USSD
            count = countUtils.getOutgoingCount(accountUuid, network,
                    new Date(startwkMutableDateTime.toDate().getTime()),
                    new Date(endwkMutableDateTime.toDate().getTime()));
            if (count > 0) {
                stats.addNetworkOutgoingUSSDCountWeek(
                        new SimpleDateFormat("MMM d").format(new Date(startwkMutableDateTime.getMillis())),
                        network, count);
            }

        }
        // get the next week
        startwkMutableDateTime.addWeeks(1);
        numWeeks++;
    } while (numWeeks < 7);

    // Set up data for the monthly bar charts               
    int numMonths = 0;
    MutableDateTime startMutableDateTime = new MutableDateTime();
    MutableDateTime endMutableDateTime;
    startMutableDateTime.setDayOfMonth(1); //get the first day of the month
    startMutableDateTime.setMillisOfDay(0); //get 00:00:00 time of the day

    //go back to 6 months
    startMutableDateTime.addMonths(-5);

    do {
        //set the end date by creating a copy
        endMutableDateTime = new MutableDateTime(startMutableDateTime);
        //push it by one month
        endMutableDateTime.addMonths(1);
        //System.out.println("Start date: " + startMutableDateTime);
        //System.out.println("End date: " + endMutableDateTime);

        for (Network network : networkList) {
            //change to use millis
            count = countUtils.getIncomingCount(accountUuid, network,
                    new Date(startMutableDateTime.toDate().getTime()),
                    new Date(endMutableDateTime.toDate().getTime()));

            if (count > 0) {
                stats.addNetworkIncomingUSSDCountMonth(
                        new SimpleDateFormat("MMM").format(new Date(startMutableDateTime.getMillis())), network,
                        count);
            }

            //System.out.println(count);                            
        }
        //get the next month
        startMutableDateTime.addMonths(1);
        numMonths++;
    } while (numMonths < 6);

    return stats;
}

From source file:net.danlew.android.joda.ZoneInfoCompiler.java

License:Apache License

static int parseTime(String str) {
    DateTimeFormatter p = ISODateTimeFormat.hourMinuteSecondFraction();
    MutableDateTime mdt = new MutableDateTime(0, getLenientISOChronology());
    int pos = 0;/*from  ww  w  .ja v a  2s.co m*/
    if (str.startsWith("-")) {
        pos = 1;
    }
    int newPos = p.parseInto(mdt, str, pos);
    if (newPos == ~pos) {
        throw new IllegalArgumentException(str);
    }
    int millis = (int) mdt.getMillis();
    if (pos == 1) {
        millis = -millis;
    }
    return millis;
}

From source file:org.apache.hive.common.util.TimestampParser.java

License:Apache License

/**
 * Parse the input string and return a timestamp value
 * @param strValue//ww  w  .  ja v  a  2  s .co  m
 * @return
 * @throws IllegalArgumentException if input string cannot be parsed into timestamp
 */
public Timestamp parseTimestamp(String strValue) throws IllegalArgumentException {
    if (fmt != null) {
        // reset value in case any date fields are missing from the date pattern
        MutableDateTime mdt = new MutableDateTime(startingDateValue);

        // Using parseInto() avoids throwing exception when parsing,
        // allowing fallback to default timestamp parsing if custom patterns fail.
        int ret = fmt.parseInto(mdt, strValue, 0);
        // Only accept parse results if we parsed the entire string
        if (ret == strValue.length()) {
            return new Timestamp(mdt.getMillis());
        }
    }

    // Otherwise try default timestamp parsing
    return Timestamp.valueOf(strValue);
}

From source file:org.apache.wicket.extensions.yui.calendar.DateTimeField.java

License:Apache License

/**
 * Sets the converted input, which is an instance of {@link Date}, possibly null. It combines
 * the inputs of the nested date, hours, minutes and am/pm fields and constructs a date from it.
 * <p>/*from w ww .j a va2 s . c  om*/
 * Note that overriding this method is a better option than overriding {@link #updateModel()}
 * like the first versions of this class did. The reason for that is that this method can be
 * used by form validators without having to depend on the actual model being updated, and this
 * method is called by the default implementation of {@link #updateModel()} anyway (so we don't
 * have to override that anymore).
 */
@Override
protected void convertInput() {
    try {
        // Get the converted input values
        Date dateFieldInput = dateField.getConvertedInput();
        Integer hoursInput = hoursField.getConvertedInput();
        Integer minutesInput = minutesField.getConvertedInput();
        AM_PM amOrPmInput = amOrPmChoice.getConvertedInput();

        if (dateFieldInput == null) {
            return;
        }

        // Get year, month and day ignoring any timezone of the Date object
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateFieldInput);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hours = (hoursInput == null ? 0 : hoursInput % 24);
        int minutes = (minutesInput == null ? 0 : minutesInput);

        // Use the input to create a date object with proper timezone
        MutableDateTime date = new MutableDateTime(year, month, day, hours, minutes, 0, 0,
                DateTimeZone.forTimeZone(getClientTimeZone()));

        // Adjust for halfday if needed
        if (use12HourFormat()) {
            int halfday = (amOrPmInput == AM_PM.PM ? 1 : 0);
            date.set(DateTimeFieldType.halfdayOfDay(), halfday);
            date.set(DateTimeFieldType.hourOfHalfday(), hours % 12);
        }

        // The date will be in the server's timezone
        setConvertedInput(new Date(date.getMillis()));
    } catch (RuntimeException e) {
        DateTimeField.this.error(e.getMessage());
        invalid();
    }
}

From source file:org.calrissian.accumulorecipes.commons.support.TimeUnit.java

License:Apache License

public long normalize(long timestamp) {
    MutableDateTime ts = new MutableDateTime(timestamp, DateTimeZone.UTC);

    /**/*  w w w.  j  a  v a  2 s .c  om*/
     * NOTE: order of switch matters.
     *
     * This switch is designed to fall through from most to least significant. Zeroes all non significant
     * portions of the time before finally breaking at the end.
     */
    switch (this) {
    case MONTHS:
        ts.setDayOfMonth(1);
    case DAYS:
        ts.setHourOfDay(0);
    case HOURS:
        ts.setMinuteOfHour(0);
    case MINUTES:
        ts.setSecondOfMinute(0);
        ts.setMillisOfSecond(0);
        break;
    default:
        throw new IllegalArgumentException("Unsupported time unit");
    }

    return ts.getMillis();
}

From source file:org.codelibs.elasticsearch.common.joda.DateMathParser.java

License:Apache License

private long parseMath(String mathString, long time, boolean roundUp, DateTimeZone timeZone)
        throws ElasticsearchParseException {
    if (timeZone == null) {
        timeZone = DateTimeZone.UTC;// w w w . ja  va 2 s . com
    }
    MutableDateTime dateTime = new MutableDateTime(time, timeZone);
    for (int i = 0; i < mathString.length();) {
        char c = mathString.charAt(i++);
        final boolean round;
        final int sign;
        if (c == '/') {
            round = true;
            sign = 1;
        } else {
            round = false;
            if (c == '+') {
                sign = 1;
            } else if (c == '-') {
                sign = -1;
            } else {
                throw new ElasticsearchParseException("operator not supported for date math [{}]", mathString);
            }
        }

        if (i >= mathString.length()) {
            throw new ElasticsearchParseException("truncated date math [{}]", mathString);
        }

        final int num;
        if (!Character.isDigit(mathString.charAt(i))) {
            num = 1;
        } else {
            int numFrom = i;
            while (i < mathString.length() && Character.isDigit(mathString.charAt(i))) {
                i++;
            }
            if (i >= mathString.length()) {
                throw new ElasticsearchParseException("truncated date math [{}]", mathString);
            }
            num = Integer.parseInt(mathString.substring(numFrom, i));
        }
        if (round) {
            if (num != 1) {
                throw new ElasticsearchParseException("rounding `/` can only be used on single unit types [{}]",
                        mathString);
            }
        }
        char unit = mathString.charAt(i++);
        MutableDateTime.Property propertyToRound = null;
        switch (unit) {
        case 'y':
            if (round) {
                propertyToRound = dateTime.yearOfCentury();
            } else {
                dateTime.addYears(sign * num);
            }
            break;
        case 'M':
            if (round) {
                propertyToRound = dateTime.monthOfYear();
            } else {
                dateTime.addMonths(sign * num);
            }
            break;
        case 'w':
            if (round) {
                propertyToRound = dateTime.weekOfWeekyear();
            } else {
                dateTime.addWeeks(sign * num);
            }
            break;
        case 'd':
            if (round) {
                propertyToRound = dateTime.dayOfMonth();
            } else {
                dateTime.addDays(sign * num);
            }
            break;
        case 'h':
        case 'H':
            if (round) {
                propertyToRound = dateTime.hourOfDay();
            } else {
                dateTime.addHours(sign * num);
            }
            break;
        case 'm':
            if (round) {
                propertyToRound = dateTime.minuteOfHour();
            } else {
                dateTime.addMinutes(sign * num);
            }
            break;
        case 's':
            if (round) {
                propertyToRound = dateTime.secondOfMinute();
            } else {
                dateTime.addSeconds(sign * num);
            }
            break;
        default:
            throw new ElasticsearchParseException("unit [{}] not supported for date math [{}]", unit,
                    mathString);
        }
        if (propertyToRound != null) {
            if (roundUp) {
                // we want to go up to the next whole value, even if we are already on a rounded value
                propertyToRound.add(1);
                propertyToRound.roundFloor();
                dateTime.addMillis(-1); // subtract 1 millisecond to get the largest inclusive value
            } else {
                propertyToRound.roundFloor();
            }
        }
    }
    return dateTime.getMillis();
}

From source file:org.codelibs.elasticsearch.common.joda.DateMathParser.java

License:Apache License

private long parseDateTime(String value, DateTimeZone timeZone, boolean roundUpIfNoTime) {
    DateTimeFormatter parser = dateTimeFormatter.parser();
    if (timeZone != null) {
        parser = parser.withZone(timeZone);
    }/*from  ww w.ja  va  2  s .co m*/
    try {
        MutableDateTime date;
        // We use 01/01/1970 as a base date so that things keep working with date
        // fields that are filled with times without dates
        if (roundUpIfNoTime) {
            date = new MutableDateTime(1970, 1, 1, 23, 59, 59, 999, DateTimeZone.UTC);
        } else {
            date = new MutableDateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
        }
        final int end = parser.parseInto(date, value, 0);
        if (end < 0) {
            int position = ~end;
            throw new IllegalArgumentException("Parse failure at index [" + position + "] of [" + value + "]");
        } else if (end != value.length()) {
            throw new IllegalArgumentException(
                    "Unrecognized chars at the end of [" + value + "]: [" + value.substring(end) + "]");
        }
        return date.getMillis();
    } catch (IllegalArgumentException e) {
        throw new ElasticsearchParseException("failed to parse date field [{}] with format [{}]", e, value,
                dateTimeFormatter.format());
    }
}

From source file:org.elasticsearch.common.joda.DateMathParser.java

License:Apache License

private long parseMath(String mathString, long time, boolean roundUp) throws ElasticsearchParseException {
    MutableDateTime dateTime = new MutableDateTime(time, DateTimeZone.UTC);
    try {//from w ww . ja  v  a2 s  .c o  m
        for (int i = 0; i < mathString.length();) {
            char c = mathString.charAt(i++);
            int type;
            if (c == '/') {
                type = 0;
            } else if (c == '+') {
                type = 1;
            } else if (c == '-') {
                type = 2;
            } else {
                throw new ElasticsearchParseException(
                        "operator not supported for date math [" + mathString + "]");
            }

            int num;
            if (!Character.isDigit(mathString.charAt(i))) {
                num = 1;
            } else {
                int numFrom = i;
                while (Character.isDigit(mathString.charAt(i))) {
                    i++;
                }
                num = Integer.parseInt(mathString.substring(numFrom, i));
            }
            if (type == 0) {
                // rounding is only allowed on whole numbers
                if (num != 1) {
                    throw new ElasticsearchParseException(
                            "rounding `/` can only be used on single unit types [" + mathString + "]");
                }
            }
            char unit = mathString.charAt(i++);
            switch (unit) {
            case 'y':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.yearOfCentury().roundCeiling();
                    } else {
                        dateTime.yearOfCentury().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addYears(num);
                } else if (type == 2) {
                    dateTime.addYears(-num);
                }
                break;
            case 'M':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.monthOfYear().roundCeiling();
                    } else {
                        dateTime.monthOfYear().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addMonths(num);
                } else if (type == 2) {
                    dateTime.addMonths(-num);
                }
                break;
            case 'w':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.weekOfWeekyear().roundCeiling();
                    } else {
                        dateTime.weekOfWeekyear().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addWeeks(num);
                } else if (type == 2) {
                    dateTime.addWeeks(-num);
                }
                break;
            case 'd':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.dayOfMonth().roundCeiling();
                    } else {
                        dateTime.dayOfMonth().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addDays(num);
                } else if (type == 2) {
                    dateTime.addDays(-num);
                }
                break;
            case 'h':
            case 'H':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.hourOfDay().roundCeiling();
                    } else {
                        dateTime.hourOfDay().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addHours(num);
                } else if (type == 2) {
                    dateTime.addHours(-num);
                }
                break;
            case 'm':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.minuteOfHour().roundCeiling();
                    } else {
                        dateTime.minuteOfHour().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addMinutes(num);
                } else if (type == 2) {
                    dateTime.addMinutes(-num);
                }
                break;
            case 's':
                if (type == 0) {
                    if (roundUp) {
                        dateTime.secondOfMinute().roundCeiling();
                    } else {
                        dateTime.secondOfMinute().roundFloor();
                    }
                } else if (type == 1) {
                    dateTime.addSeconds(num);
                } else if (type == 2) {
                    dateTime.addSeconds(-num);
                }
                break;
            default:
                throw new ElasticsearchParseException(
                        "unit [" + unit + "] not supported for date math [" + mathString + "]");
            }
        }
    } catch (Exception e) {
        if (e instanceof ElasticsearchParseException) {
            throw (ElasticsearchParseException) e;
        }
        throw new ElasticsearchParseException("failed to parse date math [" + mathString + "]");
    }
    return dateTime.getMillis();
}

From source file:org.elasticsearch.common.joda.DateMathParser.java

License:Apache License

private long parseRoundCeilStringValue(String value) {
    try {/*from ww w. j  a  v  a  2  s .c  o  m*/
        // we create a date time for inclusive upper range, we "include" by default the day level data
        // so something like 2011-01-01 will include the full first day of 2011.
        // we also use 1970-01-01 as the base for it so we can handle searches like 10:12:55 (just time)
        // since when we index those, the base is 1970-01-01
        MutableDateTime dateTime = new MutableDateTime(1970, 1, 1, 23, 59, 59, 999, DateTimeZone.UTC);
        int location = dateTimeFormatter.parser().parseInto(dateTime, value, 0);
        // if we parsed all the string value, we are good
        if (location == value.length()) {
            return dateTime.getMillis();
        }
        // if we did not manage to parse, or the year is really high year which is unreasonable
        // see if its a number
        if (location <= 0 || dateTime.getYear() > 5000) {
            try {
                long time = Long.parseLong(value);
                return timeUnit.toMillis(time);
            } catch (NumberFormatException e1) {
                throw new ElasticsearchParseException(
                        "failed to parse date field [" + value + "], tried both date format ["
                                + dateTimeFormatter.format() + "], and timestamp number");
            }
        }
        return dateTime.getMillis();
    } catch (RuntimeException e) {
        try {
            long time = Long.parseLong(value);
            return timeUnit.toMillis(time);
        } catch (NumberFormatException e1) {
            throw new ElasticsearchParseException("failed to parse date field [" + value
                    + "], tried both date format [" + dateTimeFormatter.format() + "], and timestamp number",
                    e);
        }
    }
}

From source file:org.elasticsearch.license.DateUtils.java

License:Open Source License

public static long endOfTheDay(String date) {
    try {//from   w  w  w  . j  a v a 2s .c  o m
        // Try parsing using complete date/time format
        return dateTimeFormatter.parseDateTime(date).getMillis();
    } catch (IllegalArgumentException ex) {
        // Fall back to the date only format
        MutableDateTime dateTime = dateOnlyFormatter.parseMutableDateTime(date);
        dateTime.millisOfDay().set(dateTime.millisOfDay().getMaximumValue());
        return dateTime.getMillis();
    }
}