Example usage for org.joda.time DateTime getMillis

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

Introduction

In this page you can find the example usage for org.joda.time DateTime 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:com.splicemachine.db.iapi.types.SQLTimestamp.java

License:Apache License

private void setNumericTimestamp(DateTime dt) throws StandardException {
    if (SanityManager.DEBUG) {
        SanityManager.ASSERT(isNull(), "setNumericTimestamp called when already set");
    }//from   w  w w . ja va2 s  .  com
    if (dt != null) {
        int nanosLocal;
        nanosLocal = (int) ((dt.getMillis() % 1000) * 1000000);
        if (nanosLocal < 0) {
            nanosLocal = 1000000000 + nanosLocal;
        }
        setValue(computeEncodedDate(dt), computeEncodedTime(dt), nanosLocal);
    }
    /* encoded date should already be 0 for null */
}

From source file:com.splicemachine.derby.utils.SpliceDateFunctions.java

License:Apache License

private static long parseDateTime(String source, String format) throws SQLException {
    // FIXME: Timezone loss for Timestamp - see http://stackoverflow.com/questions/16794772/joda-time-parse-a-date-with-timezone-and-retain-that-timezone
    DateTimeFormatter parser = DEFAULT_DATE_TIME_FORMATTER;
    if (format != null) {
        try {//from  ww  w .j  av a 2  s .c  o  m
            parser = DateTimeFormat.forPattern(format);
        } catch (Exception e) {
            throw new SQLException("Error creating a datetime parser for pattern: " + format + ". Try using an"
                    + " ISO8601 pattern such as, yyyy-MM-dd'T'HH:mm:ss.SSSZZ, yyyy-MM-dd'T'HH:mm:ssZ or yyyy-MM-dd",
                    SQLState.LANG_DATE_SYNTAX_EXCEPTION);
        }
    }
    DateTime parsed;
    try {
        parsed = parser.withOffsetParsed().parseDateTime(source);
    } catch (Exception e) {
        throw new SQLException("Error parsing datetime " + source + " with pattern: " + format
                + ". Try using an"
                + " ISO8601 pattern such as, yyyy-MM-dd'T'HH:mm:ss.SSSZZ, yyyy-MM-dd'T'HH:mm:ssZ or yyyy-MM-dd",
                SQLState.LANG_DATE_SYNTAX_EXCEPTION);
    }
    return parsed.getMillis();
}

From source file:com.splicemachine.derby.utils.SpliceDateFunctions.java

License:Apache License

public static Date LAST_DAY(Date source) {
    if (source == null) {
        return null;
    }/*  w  w w . j ava2s.  c  o  m*/
    DateTime dt = new DateTime(source).dayOfMonth().withMaximumValue();
    return new Date(dt.getMillis());
}

From source file:com.splicemachine.derby.utils.SpliceDateFunctions.java

License:Apache License

/**
 * Implements the trunc_date function/* w  w  w. j  av a  2 s  .  c o  m*/
 */
public static Timestamp TRUNC_DATE(Timestamp source, String field) throws SQLException {
    if (source == null || field == null)
        return null;
    DateTime dt = new DateTime(source);
    field = field.toLowerCase();
    String lowerCaseField = field.toLowerCase();
    if ("microseconds".equals(lowerCaseField)) {
        int nanos = source.getNanos();
        nanos = nanos - nanos % 1000;
        source.setNanos(nanos);
        return source;
    } else if ("milliseconds".equals(lowerCaseField)) {
        int nanos = source.getNanos();
        nanos = nanos - nanos % 1000000;
        source.setNanos(nanos);
        return source;
    } else if ("second".equals(lowerCaseField)) {
        source.setNanos(0);
        return source;

    } else if ("minute".equals(lowerCaseField)) {
        DateTime modified = dt.minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("hour".equals(lowerCaseField)) {
        DateTime modified = dt.minusMinutes(dt.getMinuteOfHour()).minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("day".equals(lowerCaseField)) {
        DateTime modified = dt.minusHours(dt.getHourOfDay()).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("week".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.getDayOfWeek()).minusHours(dt.getHourOfDay())
                .minusMinutes(dt.getMinuteOfHour()).minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("month".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusHours(dt.getHourOfDay()).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("quarter".equals(lowerCaseField)) {
        int month = dt.getMonthOfYear();
        DateTime modified = dt;
        if ((month + 1) % 3 == 1) {
            modified = dt.minusMonths(2);
        } else if ((month + 1) % 3 == 0) {
            modified = dt.minusMonths(1);
        }
        DateTime fin = modified.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusHours(dt.getHourOfDay()).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(fin.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("year".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusHours(dt.getHourOfDay()).minusMonths(dt.getMonthOfYear() - 1)
                .minusMinutes(dt.getMinuteOfHour()).minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("decade".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusYears(dt.getYear() % 10).minusHours(dt.getHourOfDay())
                .minusMonths(dt.getMonthOfYear() - 1).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("century".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusHours(dt.getHourOfDay()).minusYears(dt.getYear() % 100)
                .minusMonths(dt.getMonthOfYear() - 1).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("millennium".equals(lowerCaseField)) {
        int newYear = dt.getYear() - dt.getYear() % 1000;
        //noinspection deprecation (converstion from joda to java.sql.Timestamp did not work for millennium < 2000)
        return new Timestamp(newYear - 1900, Calendar.JANUARY, 1, 0, 0, 0, 0);
    } else {
        throw new SQLException(String.format("invalid time unit '%s'", field));
    }
}

From source file:com.spotify.reaper.resources.view.RepairRunStatus.java

License:Apache License

public RepairRunStatus(long runId, String clusterName, String keyspaceName, Collection<String> columnFamilies,
        int segmentsRepaired, int totalSegments, RepairRun.RunState state, DateTime startTime, DateTime endTime,
        String cause, String owner, String lastEvent, DateTime creationTime, DateTime pauseTime,
        double intensity, RepairParallelism repairParallelism) {
    this.id = runId;
    this.cause = cause;
    this.owner = owner;
    this.clusterName = clusterName;
    this.columnFamilies = columnFamilies;
    this.keyspaceName = keyspaceName;
    this.state = state;
    this.creationTime = creationTime;
    this.startTime = startTime;
    this.endTime = endTime;
    this.pauseTime = pauseTime;
    this.intensity = CommonTools.roundDoubleNicely(intensity);
    this.totalSegments = totalSegments;
    this.repairParallelism = repairParallelism;
    this.segmentsRepaired = segmentsRepaired;
    this.lastEvent = lastEvent;

    if (startTime == null || endTime == null) {
        duration = null;//ww  w.  j  a  v a2  s.c  o m
    } else {
        duration = DurationFormatUtils.formatDurationWords(
                new Duration(startTime.toInstant(), endTime.toInstant()).getMillis(), true, false);
    }

    if (startTime == null || endTime != null) {
        estimatedTimeOfArrival = null;
    } else {
        if (state == RepairRun.RunState.ERROR || state == RepairRun.RunState.DELETED
                || state == RepairRun.RunState.ABORTED) {
            estimatedTimeOfArrival = null;
        } else if (segmentsRepaired == 0) {
            estimatedTimeOfArrival = null;
        } else {
            long now = DateTime.now().getMillis();
            long currentDuration = now - startTime.getMillis();
            long millisecondsPerSegment = currentDuration / segmentsRepaired;
            int segmentsLeft = totalSegments - segmentsRepaired;
            estimatedTimeOfArrival = new DateTime(now + millisecondsPerSegment * segmentsLeft);
        }
    }
}

From source file:com.squarespace.template.plugins.PluginDateUtils.java

License:Apache License

/**
 * Takes a strftime()-compatible format string and outputs the properly formatted date.
 *///from   ww w  .  j a va 2s .  co  m
public static void formatDate(Locale locale, String fmt, long instant, String tzName, StringBuilder buf) {
    DateTimeZone zone = null;
    try {
        zone = DateTimeZone.forID(tzName);
    } catch (IllegalArgumentException e) {
        zone = DateTimeZone.getDefault();
    }
    DateTime date = new DateTime(instant, zone);
    int index = 0;
    int len = fmt.length();
    while (index < len) {
        char c1 = fmt.charAt(index);
        index++;
        if (c1 != '%' || index == len) {
            buf.append(c1);
            continue;
        }
        char c2 = fmt.charAt(index);
        switch (c2) {
        case 'A':
            buf.append(date.dayOfWeek().getAsText(locale));
            break;
        case 'a':
            buf.append(date.dayOfWeek().getAsShortText(locale));
            break;
        case 'B':
            buf.append(date.monthOfYear().getAsText(locale));
            break;
        case 'b':
            buf.append(date.monthOfYear().getAsShortText(locale));
            break;
        case 'C':
            leftPad(date.centuryOfEra().get(), '0', 2, buf);
            break;
        case 'c':
            formatAggregate(DateTimeAggregate.FULL, locale, date, buf);
            break;
        case 'D':
            formatAggregate(DateTimeAggregate.MMDDYY, locale, date, buf);
            break;
        case 'd':
            leftPad(date.dayOfMonth().get(), '0', 2, buf);
            break;
        case 'e':
            leftPad(date.dayOfMonth().get(), ' ', 2, buf);
            break;
        case 'F':
            formatAggregate(DateTimeAggregate.YYYYMMDD, locale, date, buf);
            break;
        case 'G':
            buf.append(date.year().get());
            break;
        case 'g':
            leftPad(date.yearOfCentury().get(), '0', 2, buf);
            break;
        case 'H':
            leftPad(date.hourOfDay().get(), '0', 2, buf);
            break;
        case 'h':
            buf.append(date.monthOfYear().getAsShortText(locale));
            break;
        case 'I':
            leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), '0', 2, buf);
            break;
        case 'j':
            leftPad(date.dayOfYear().get(), '0', 3, buf);
            break;
        case 'k':
            leftPad(date.get(DateTimeFieldType.clockhourOfDay()), ' ', 2, buf);
            break;
        case 'l':
            leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), ' ', 2, buf);
            break;
        case 'M':
            leftPad(date.minuteOfHour().get(), '0', 2, buf);
            break;
        case 'm':
            leftPad(date.monthOfYear().get(), '0', 2, buf);
            break;
        case 'n':
            buf.append('\n');
            break;
        case 'P':
            buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "am" : "pm");
            break;
        case 'p':
            buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
            break;
        case 'R':
            formatAggregate(DateTimeAggregate.H240_M0, locale, date, buf);
            break;
        case 'S':
            leftPad(date.secondOfMinute().get(), '0', 2, buf);
            break;
        case 's':
            buf.append(instant / 1000);
            break;
        case 't':
            buf.append('\t');
            break;
        case 'T':
            // Equivalent of %H:%M:%S
            formatAggregate(DateTimeAggregate.H240_M0, locale, date, buf);
            buf.append(':');
            leftPad(date.secondOfMinute().get(), '0', 2, buf);
            break;

        case 'U':
            // TODO: fix week-of-year number
            leftPad(date.weekOfWeekyear().get(), '0', 2, buf);
            break;

        case 'u':
            buf.append(date.dayOfWeek().get());
            break;

        case 'V':
            // TODO: fix week-of-year number
            leftPad(date.weekOfWeekyear().get(), '0', 2, buf);
            break;

        case 'v':
            // Equivalent of %e-%b-%Y
            leftPad(date.dayOfMonth().get(), ' ', 2, buf);
            buf.append('-');
            buf.append(date.monthOfYear().getAsShortText());
            buf.append('-');
            buf.append(date.getYear());
            break;

        case 'W':
            // TODO: fix week-of-year number
            break;

        case 'w':
            buf.append(date.dayOfWeek().get());
            break;
        case 'X':
            formatAggregate(DateTimeAggregate.HHMMSSP, locale, date, buf);
            break;
        case 'x':
            formatAggregate(DateTimeAggregate.MMDDYYYY, locale, date, buf);
            break;
        case 'Y':
            buf.append(date.getYear());
            break;
        case 'y':
            leftPad(date.getYearOfCentury(), '0', 2, buf);
            break;

        case 'Z':
            // Note: Joda's nameKey happens to be the same as the shortName. Making
            // this change to workaround Joda https://github.com/JodaOrg/joda-time/issues/288
            buf.append(zone.getNameKey(date.getMillis()));
            break;

        case 'z':
            int offset = date.getZone().getOffset(instant) / 60000;
            int hours = (int) Math.floor(offset / 60);
            int minutes = (hours * 60) - offset;
            if (offset < 0) {
                buf.append('-');
            }
            leftPad(Math.abs(hours), '0', 2, buf);
            leftPad(Math.abs(minutes), '0', 2, buf);
            break;

        default:
            // no match, emit literals.
            buf.append(c1).append(c2);
        }
        index++;
    }
}

From source file:com.squarespace.template.plugins.PluginDateUtils.java

License:Apache License

private static void formatAggregate(DateTimeAggregate type, Locale locale, DateTime date, StringBuilder buf) {
    switch (type) {
    case FULL:/*  ww w  . ja va2 s  . c  o  m*/
        buf.append(date.dayOfWeek().getAsShortText(locale));
        buf.append(' ');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.monthOfYear().getAsShortText(locale));
        buf.append(' ');
        buf.append(date.year().get());
        buf.append(' ');
        leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), '0', 2, buf);
        buf.append(':');
        leftPad(date.minuteOfHour().get(), '0', 2, buf);
        buf.append(':');
        leftPad(date.secondOfMinute().get(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
        buf.append(' ');
        buf.append(date.getZone().getNameKey(date.getMillis()));
        break;

    case H240_M0:
        leftPad(date.get(DateTimeFieldType.clockhourOfDay()), '0', 2, buf);
        buf.append(':');
        leftPad(date.minuteOfHour().get(), '0', 2, buf);
        break;

    case HHMMSSP:
        leftPad(date.get(DateTimeFieldType.hourOfHalfday()), '0', 2, buf);
        buf.append(':');
        leftPad(date.getMinuteOfHour(), '0', 2, buf);
        buf.append(':');
        leftPad(date.getSecondOfMinute(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
        break;

    case MMDDYY:
        leftPad(date.getMonthOfYear(), '0', 2, buf);
        buf.append('/');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append('/');
        leftPad(date.yearOfCentury().get(), '0', 2, buf);
        break;

    case MMDDYYYY:
        leftPad(date.getMonthOfYear(), '0', 2, buf);
        buf.append('/');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append('/');
        buf.append(date.getYear());
        break;

    case YYYYMMDD:
        buf.append(date.year().get());
        buf.append('-');
        leftPad(date.monthOfYear().get(), '0', 2, buf);
        buf.append('-');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        break;

    default:
        break;
    }
}

From source file:com.srotya.tau.dengine.validation.DateInterceptor.java

License:Apache License

@Override
public void validate(JsonObject event) throws ValidationException {
    try {//from   w w  w .  j a v  a2s. co  m
        DateTime ts = formatter.parseDateTime(event.get(dateField).getAsString());
        event.remove(dateField);
        event.addProperty(dateField, ts.getMillis());
        if (next != null) {
            next.validate(event);
        }
    } catch (Exception e) {
        throw new ValidationException(e.getMessage());
    }
}

From source file:com.srotya.tau.nucleus.api.DateInterceptor.java

License:Apache License

@Override
public void validate(Map<String, Object> eventHeaders) throws ValidationException {
    try {//  w  w  w . j av  a 2  s .  c o  m
        DateTime ts = formatter.parseDateTime(eventHeaders.get(dateField).toString());
        eventHeaders.remove(dateField);
        eventHeaders.put(Constants.FIELD_TIMESTAMP, ts.getMillis());
        if (next != null) {
            next.validate(eventHeaders);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new ValidationException(e.getMessage());
    }
}

From source file:com.stratio.ingestion.serializer.elasticsearch.ElasticSearchSerializerWithMapping.java

License:Apache License

TimestampedEvent(Event base) {
    super();/*from   w w w.  j av a 2 s . c  om*/
    setBody(base.getBody());
    Map<String, String> headers = Maps.newHashMap(base.getHeaders());

    String timestampHeader = headers.get("@timestamp");
    Long ts = null;
    if (!StringUtils.isBlank(timestampHeader)) {
        try {
            ts = Long.parseLong(timestampHeader);
            headers.put("@timestamp", ISODateTimeFormat.dateTime().withZoneUTC().print(ts));
        } catch (RuntimeException ex) {
            log.trace("Could not parse timestamp as long: {}", timestampHeader);
            try {
                ts = ISODateTimeFormat.dateOptionalTimeParser().withZoneUTC().parseMillis(timestampHeader);
            } catch (RuntimeException ex2) {
                log.trace("Could not parse timestamp as dateOptionalTime: {}", timestampHeader);
            }
        }
    }

    if (ts == null) {
        DateTime now = DateTime.now();
        ts = now.getMillis();
        headers.put("@timestamp", ISODateTimeFormat.dateTime().withZoneUTC().print(now));
    }

    this.timestamp = ts;

    setHeaders(headers);
}