Example usage for org.joda.time DateTime getChronology

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

Introduction

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

Prototype

public Chronology getChronology() 

Source Link

Document

Gets the chronology of the datetime.

Usage

From source file:ar.com.wolox.commons.base.json.JSONSerializableDateTime.java

License:Apache License

/**
 * Creates a {@link JSONSerializableDateTime} from a {@link DateTime}
 *
 * @param date//from ww w. ja  v  a  2  s.  com
 * @return
 */
public static JSONSerializableDateTime create(@NotNull final DateTime date) {
    if (date == null) {
        throw new IllegalArgumentException("The date to be serialized cannot be null");
    }

    final JSONSerializableDateTime serialized = new JSONSerializableDateTime();
    serialized.setIsoDate(ISODateTimeFormat.dateTime().print(date));
    serialized.setTimeZone(date.getChronology().getZone().getID());
    return serialized;
}

From source file:com.facebook.util.TimeIntervalType.java

License:Apache License

/**
 * Gets the start instant given the event instant, interval length 
 * and the time zone for this interval type.
 * /*  w w w . j  a  v a 2s . c om*/
 * @param instant the event time instant.
 * @param length the interval length
 * 
 * @return the start instant of the interval of given length that contains 
 * the supplied time instant in the supplied time zone 
 */
public DateTime getTimeIntervalStart(DateTime instant, long length) {
    validateValue(instant.getZone(), length);
    // Get the time in the specified timezone
    DateTime periodStart = instant;
    // Clear all the fields for this intervalType and its subtypes
    TimeIntervalType timeIntervalType = this;
    while (timeIntervalType != null) {
        periodStart = timeIntervalType.clearField(periodStart);
        timeIntervalType = timeIntervalType.subType;
    }
    // figure out the which time interval does the instant lie in
    Period period = new Period(periodStart, instant, periodType);
    DurationField durationField = fieldType.getField(instant.getChronology()).getDurationField();
    int diff = period.get(durationField.getType());
    long startDelta = (diff / length) * length;
    return periodStart.withFieldAdded(durationField.getType(), FieldUtils.safeToInt(startDelta));
}

From source file:com.facebook.util.TimeIntervalType.java

License:Apache License

protected DateTime clearField(DateTime value) {
    return value.withField(fieldType, fieldType.getField(value.getChronology()).getMinimumValue());
}

From source file:com.github.jasonruckman.sidney.ext.common.JodaDateTimeSerializer.java

License:Apache License

@Override
public void writeValue(DateTime value, Contexts.WriteContext context) {
    millis.writeLong(value.getMillis(), context);
    chrono.writeValue(value.getChronology(), context);
    tz.writeValue(value.getZone().getID(), context);
}

From source file:com.googlecode.icegem.serialization.serializers.JodaTimeDataSerializer.java

License:Open Source License

@Override
public boolean toData(Object o, DataOutput dataOutput) throws IOException {
    if (o instanceof DateTime) {
        DateTime dt = (DateTime) o;
        dataOutput.writeLong(dt.getMillis());
        Chronology chronology = dt.getChronology();

        boolean customChronology = false;
        if (!chronology.getClass().getName().equals(ISOChronology.class.getName())) {
            customChronology = true;// w  w w . ja v  a2  s  . c  o m
        }

        byte flags = 0;
        boolean customTimeZone = true;

        String timeZoneId = chronology.getZone().getID();
        for (byte i = 0; i < TIMEZONE_IDS.length; i++) {
            if (timeZoneId.equals(TIMEZONE_IDS[i])) {
                flags = i;
                customTimeZone = false;
                break;
            }
        }

        if (customTimeZone) {
            flags = CUSTOM_TZ_ID;
        }

        flags |= customChronology ? (1 << 7) : 0;
        dataOutput.write(flags);

        if (customChronology) {
            dataOutput.writeUTF(chronology.getClass().getName());
        }
        if (customTimeZone) {
            dataOutput.writeUTF(chronology.getZone().getID());
        }
        return true;
    }
    return false;
}

From source file:de.javakaffee.kryoserializers.jodatime.JodaDateTimeSerializer.java

License:Apache License

@Override
public void write(final Kryo kryo, final Output output, final DateTime obj) {
    output.writeLong(obj.getMillis(), true);
    final String chronologyId = getChronologyId(obj.getChronology());
    output.writeString(chronologyId == null ? "" : chronologyId);

    if (obj.getZone() != null && obj.getZone() != DateTimeZone.getDefault())
        output.writeString(obj.getZone().getID());
    else/*from   ww w  .j  a  v a 2  s .c o  m*/
        output.writeString("");
}

From source file:de.javakaffee.web.msm.serializer.javolution.JodaDateTimeFormat.java

License:Apache License

/**
 * {@inheritDoc}//from   w w w .j  a  va 2  s.c om
 */
@Override
public void write(final DateTime obj, final javolution.xml.XMLFormat.OutputElement output)
        throws XMLStreamException {
    output.setAttribute(MILLIS, obj.getMillis());
    final String chronologyId = getChronologyId(obj.getChronology());
    if (chronologyId != null) {
        output.setAttribute(CHRONOLOGY, chronologyId);
    }
    if (obj.getZone() != null && obj.getZone() != DateTimeZone.getDefault()) {
        output.setAttribute(TIME_ZONE, obj.getZone().getID());
    }
}

From source file:name.martingeisse.wicket.panel.simple.DateTimeTextFieldPanel.java

License:Open Source License

@Override
protected void onBeforeRender() {
    final Class<?> modelType = getType();
    final Object modelObject = getDefaultModelObject();
    if (modelType == DateTime.class) {
        final DateTime modelDateTime = (DateTime) modelObject;
        originalChronology = modelDateTime.getChronology();
        localizedChronology = originalChronology.withZone(MyWicketSession.get().getTimeZone());
        final DateTime localizedModelDateTime = modelDateTime.withChronology(localizedChronology);
        date = localizedModelDateTime.toLocalDate();
        time = localizedModelDateTime.toLocalTime();
    } else if (modelType == LocalDateTime.class) {
        final LocalDateTime modelDateTime = (LocalDateTime) modelObject;
        originalChronology = modelDateTime.getChronology();
        localizedChronology = originalChronology;
        date = modelDateTime.toLocalDate();
        time = modelDateTime.toLocalTime();
    } else {/* www  .j ava 2  s .  c o  m*/
        throw new IllegalStateException("unsupported model type for DateTimeTextFieldPanel: " + modelType);
    }
    super.onBeforeRender();
}

From source file:org.apache.druid.java.util.common.granularity.DurationGranularity.java

License:Apache License

@Override
public DateTime bucketStart(DateTime time) {
    long t = time.getMillis();
    final long duration = getDurationMillis();
    long offset = t % duration - origin;
    if (offset < 0) {
        offset += duration;//from   w ww .  j av a 2s  .c  o  m
    }
    return new DateTime(t - offset, time.getChronology());
}

From source file:org.graylog2.indexer.rotation.strategies.TimeBasedRotationStrategy.java

License:Open Source License

/**
 * Determines the starting point ("anchor") for a period.
 *
 * To produce repeatable rotation points in time, the period is "snapped" to a "grid" of time.
 * For example, an hourly index rotation would be anchored to the last full hour, instead of happening at whatever minute
 * the first rotation was started./*from w  ww .  jav  a 2 s .c  o  m*/
 *
 * This "snapping" is done accordingly with the other parts of a period.
 *
 * For highly irregular periods (those that do not have a small zero component)
 *
 * @param period the rotation period
 * @return the anchor DateTime to calculate rotation periods from
 */
protected static DateTime determineRotationPeriodAnchor(@Nullable DateTime lastAnchor, Period period) {
    final Period normalized = period.normalizedStandard();
    int years = normalized.getYears();
    int months = normalized.getMonths();
    int weeks = normalized.getWeeks();
    int days = normalized.getDays();
    int hours = normalized.getHours();
    int minutes = normalized.getMinutes();
    int seconds = normalized.getSeconds();

    if (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
        throw new IllegalArgumentException("Invalid rotation period specified");
    }

    // find the largest non-zero stride in the period. that's our anchor type. statement order matters here!
    DateTimeFieldType largestStrideType = null;
    if (seconds > 0)
        largestStrideType = secondOfMinute();
    if (minutes > 0)
        largestStrideType = minuteOfHour();
    if (hours > 0)
        largestStrideType = hourOfDay();
    if (days > 0)
        largestStrideType = dayOfMonth();
    if (weeks > 0)
        largestStrideType = weekOfWeekyear();
    if (months > 0)
        largestStrideType = monthOfYear();
    if (years > 0)
        largestStrideType = year();
    if (largestStrideType == null) {
        throw new IllegalArgumentException("Could not determine rotation stride length.");
    }

    final DateTime anchorTime = MoreObjects.firstNonNull(lastAnchor, Tools.nowUTC());

    final DateTimeField field = largestStrideType.getField(anchorTime.getChronology());
    // use normalized here to make sure we actually have the largestStride type available! see https://github.com/Graylog2/graylog2-server/issues/836
    int periodValue = normalized.get(largestStrideType.getDurationType());
    final long fieldValue = field.roundFloor(anchorTime.getMillis());

    final int fieldValueInUnit = field.get(fieldValue);
    if (periodValue == 0) {
        // https://github.com/Graylog2/graylog2-server/issues/836
        log.warn(
                "Determining stride length failed because of a 0 period. Defaulting back to 1 period to avoid crashing, but this is a bug!");
        periodValue = 1;
    }
    final long difference = (fieldValueInUnit % periodValue);
    final long newValue = field.add(fieldValue, -1 * difference);
    return new DateTime(newValue, DateTimeZone.UTC);
}