Example usage for org.joda.time.chrono ISOChronology getInstance

List of usage examples for org.joda.time.chrono ISOChronology getInstance

Introduction

In this page you can find the example usage for org.joda.time.chrono ISOChronology getInstance.

Prototype

public static ISOChronology getInstance(DateTimeZone zone) 

Source Link

Document

Gets an instance of the ISOChronology in the given time zone.

Usage

From source file:AgeCalculator.java

License:Apache License

private void addTopArea(Container container) {
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

    panel.add(fixedHeight(new JLabel("Birthdate")));
    panel.add(Box.createHorizontalStrut(10));

    final JTextField birthdateField = new JTextField(iBirthdateStr + ' ');
    Document doc = birthdateField.getDocument();
    doc.addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {
            update(e);//from  w w  w .  j a va  2s  . c  o m
        }

        public void removeUpdate(DocumentEvent e) {
            update(e);
        }

        public void changedUpdate(DocumentEvent e) {
            update(e);
        }

        private void update(DocumentEvent e) {
            iBirthdateStr = birthdateField.getText();
            updateResults();
        }
    });
    panel.add(fixedHeight(birthdateField));

    panel.add(Box.createHorizontalStrut(10));

    Object[] ids = DateTimeZone.getAvailableIDs().toArray();
    final JComboBox zoneSelector = new JComboBox(ids);
    zoneSelector.setSelectedItem(DateTimeZone.getDefault().getID());
    panel.add(fixedSize(zoneSelector));

    zoneSelector.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String id = (String) zoneSelector.getSelectedItem();
            iChronology = ISOChronology.getInstance(DateTimeZone.forID(id));
            updateResults();
        }
    });

    container.add(fixedHeight(panel));
}

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

License:Apache License

/**
 * Returns the number of milliseconds per unit of this interval type.
 * // ww  w  .  j a v a2s .c  o  m
 * @return the number of milliseconds per unit of this interval type.
 */
public long toDurationMillis() {
    return fieldType.getDurationType().getField(
            // Assume that durations are always in UTC
            ISOChronology.getInstance(DateTimeZone.UTC)).getUnitMillis();
}

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

License:Open Source License

@Override
public Object fromData(DataInput dataInput) throws IOException, ClassNotFoundException {
    long time = dataInput.readLong();
    byte flags = dataInput.readByte();

    boolean customChornology = ((flags & 0x80) != 0);
    byte timeZoneIndex = (byte) (flags & 0x7F);
    boolean customTimeZone = (timeZoneIndex == CUSTOM_TZ_ID);

    String chronologyClassName = null;
    DateTimeZone dateTimeZone;//from   ww  w  .j  a v a 2s. c o m

    Chronology chronology;
    if (customChornology) {
        chronologyClassName = dataInput.readUTF();
    }

    if (customTimeZone) {
        dateTimeZone = DateTimeZone.forID(dataInput.readUTF());
    } else {
        if (timeZoneIndex >= TIMEZONE_IDS.length) {
            throw new IOException("Serialized form contains unknown TZ index");
        }

        String tzId = TIMEZONE_IDS[timeZoneIndex];
        dateTimeZone = DateTimeZone.forID(tzId);
    }

    if (chronologyClassName != null) {
        Class<?> chronologyCls = Class.forName(chronologyClassName);
        try {

            Method factory = chronologyCls.getMethod("getInstance", new Class[] { DateTimeZone.class });

            chronology = (Chronology) factory.invoke(null, dateTimeZone);
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate Joda Chronology");
        }
    } else {
        chronology = ISOChronology.getInstance(dateTimeZone);
    }

    return new DateTime(time, chronology);
}

From source file:com.helger.datetime.config.PDTConfig.java

License:Apache License

/**
 * @return The default chronology ({@link ISOChronology} or
 *         {@link GJChronology}) using the result of
 *         {@link #getDefaultDateTimeZone()}
 * @see #isUseISOChronology()//  w  w  w  .j a v a 2 s . co  m
 * @see #getDefaultDateTimeZone()
 */
@Nonnull
public static Chronology getDefaultChronology() {
    if (isUseISOChronology())
        return ISOChronology.getInstance(getDefaultDateTimeZone());
    return GJChronology.getInstance(getDefaultDateTimeZone());
}

From source file:com.metamx.druid.PeriodGranularity.java

License:Open Source License

@JsonCreator
public PeriodGranularity(@JsonProperty("period") Period period, @JsonProperty("origin") DateTime origin,
        @JsonProperty("timeZone") DateTimeZone tz) {
    this.period = period;
    this.chronology = tz == null ? ISOChronology.getInstanceUTC() : ISOChronology.getInstance(tz);
    if (origin == null) {
        // default to origin in given time zone when aligning multi-period granularities
        this.origin = new DateTime(0, DateTimeZone.UTC).withZoneRetainFields(chronology.getZone()).getMillis();
        this.hasOrigin = false;
    } else {/* ww  w.  j  a  va2s  .c o m*/
        this.origin = origin.getMillis();
        this.hasOrigin = true;
    }
    this.isCompound = isCompoundPeriod(period);
}

From source file:com.phloc.datetime.config.PDTConfig.java

License:Apache License

/**
 * @return The default GJ chronology using the result of
 *         {@link #getDefaultDateTimeZone()}
 *//*from  w  ww .ja va 2  s  .  c  om*/
@Nonnull
public static Chronology getDefaultChronology() {
    if (s_bUseISOChronology)
        return ISOChronology.getInstance(getDefaultDateTimeZone());
    return GJChronology.getInstance(getDefaultDateTimeZone());
}

From source file:io.druid.java.util.common.granularity.PeriodGranularity.java

License:Apache License

@JsonCreator
public PeriodGranularity(@JsonProperty("period") Period period, @JsonProperty("origin") DateTime origin,
        @JsonProperty("timeZone") DateTimeZone tz) {
    this.period = Preconditions.checkNotNull(period, "period can't be null!");
    Preconditions.checkArgument(!Period.ZERO.equals(period),
            "zero period is not acceptable in QueryGranularity!");
    this.chronology = tz == null ? ISOChronology.getInstanceUTC() : ISOChronology.getInstance(tz);
    if (origin == null) {
        // default to origin in given time zone when aligning multi-period granularities
        this.origin = new DateTime(0, DateTimeZone.UTC).withZoneRetainFields(chronology.getZone()).getMillis();
        this.hasOrigin = false;
    } else {//from  w w  w  . j  a va  2  s .c o m
        this.origin = origin.getMillis();
        this.hasOrigin = true;
    }
    this.isCompound = isCompoundPeriod(period);
}

From source file:io.druid.query.expression.TimestampExtractExprMacro.java

License:Apache License

@Override
public Expr apply(final List<Expr> args) {
    if (args.size() < 2 || args.size() > 3) {
        throw new IAE("Function[%s] must have 2 to 3 arguments", name());
    }//from w  w  w.  j  a v  a  2s .  c  om

    if (!args.get(1).isLiteral() || args.get(1).getLiteralValue() == null) {
        throw new IAE("Function[%s] unit arg must be literal", name());
    }

    if (args.size() > 2 && !args.get(2).isLiteral()) {
        throw new IAE("Function[%s] timezone arg must be literal", name());
    }

    final Expr arg = args.get(0);
    final Unit unit = Unit.valueOf(((String) args.get(1).getLiteralValue()).toUpperCase());
    final DateTimeZone timeZone;

    if (args.size() > 2) {
        timeZone = ExprUtils.toTimeZone(args.get(2));
    } else {
        timeZone = DateTimeZone.UTC;
    }

    final ISOChronology chronology = ISOChronology.getInstance(timeZone);

    class TimestampExtractExpr implements Expr {
        @Nonnull
        @Override
        public ExprEval eval(final ObjectBinding bindings) {
            final DateTime dateTime = new DateTime(arg.eval(bindings).asLong()).withChronology(chronology);
            switch (unit) {
            case EPOCH:
                return ExprEval.of(dateTime.getMillis());
            case SECOND:
                return ExprEval.of(dateTime.secondOfMinute().get());
            case MINUTE:
                return ExprEval.of(dateTime.minuteOfHour().get());
            case HOUR:
                return ExprEval.of(dateTime.hourOfDay().get());
            case DAY:
                return ExprEval.of(dateTime.dayOfMonth().get());
            case DOW:
                return ExprEval.of(dateTime.dayOfWeek().get());
            case DOY:
                return ExprEval.of(dateTime.dayOfYear().get());
            case WEEK:
                return ExprEval.of(dateTime.weekOfWeekyear().get());
            case MONTH:
                return ExprEval.of(dateTime.monthOfYear().get());
            case QUARTER:
                return ExprEval.of((dateTime.monthOfYear().get() - 1) / 3 + 1);
            case YEAR:
                return ExprEval.of(dateTime.year().get());
            default:
                throw new ISE("Unhandled unit[%s]", unit);
            }
        }

        @Override
        public void visit(final Visitor visitor) {
            arg.visit(visitor);
            visitor.visit(this);
        }
    }

    return new TimestampExtractExpr();
}

From source file:net.asfun.jangod.lib.filter.DatetimeFilter.java

License:Apache License

@Override
public Object filter(Object object, JangodInterpreter interpreter, String... arg) throws InterpretException {
    if (object == null) {
        return object;
    }/*from  ww  w  .  j  a  va2 s  .  c  o m*/
    if (object instanceof DateTime) { // joda DateTime
        DateTimeFormatter formatter;
        DateTimeFormatter a = DateTimeFormat.forPattern(interpreter.evaluateExpressionAsString(arg[0]));
        if (arg.length == 1) {
            DateTimeFormatter forPattern = a;
            JodaTimeContext jodaTimeContext = JodaTimeContextHolder.getJodaTimeContext();
            if (jodaTimeContext == null) {
                jodaTimeContext = new JodaTimeContext();
            }
            formatter = jodaTimeContext.getFormatter(forPattern);
        } else if (arg.length == 2) {
            formatter = a.withChronology(ISOChronology
                    .getInstance(DateTimeZone.forID(interpreter.evaluateExpressionAsString(arg[1]))));
        } else {
            throw new InterpretException("filter date expects 1 or 2 args >>> " + arg.length);
        }
        return formatter.print((DateTime) object);
    } else {
        SimpleDateFormat sdf;
        if (arg.length == 1) {
            sdf = new SimpleDateFormat(interpreter.evaluateExpressionAsString(arg[0]));
            sdf.setTimeZone(interpreter.getConfiguration().getTimezone());
        } else if (arg.length == 2) {
            sdf = new SimpleDateFormat(interpreter.evaluateExpressionAsString(arg[0]));
            sdf.setTimeZone(TimeZone.getTimeZone(interpreter.evaluateExpressionAsString(arg[1])));
        } else {
            throw new InterpretException("filter date expects 1 or 2 args >>> " + arg.length);
        }
        return sdf.format(object);
    }
}

From source file:org.apache.druid.query.expression.ExprUtils.java

License:Apache License

static PeriodGranularity toPeriodGranularity(final Expr periodArg, @Nullable final Expr originArg,
        @Nullable final Expr timeZoneArg, final Expr.ObjectBinding bindings) {
    final Period period = new Period(periodArg.eval(bindings).asString());
    final DateTime origin;
    final DateTimeZone timeZone;

    if (timeZoneArg == null) {
        timeZone = null;//from   www  .  ja v  a  2  s .  c  o m
    } else {
        final String value = timeZoneArg.eval(bindings).asString();
        timeZone = value != null ? DateTimes.inferTzFromString(value) : null;
    }

    if (originArg == null) {
        origin = null;
    } else {
        Chronology chronology = timeZone == null ? ISOChronology.getInstanceUTC()
                : ISOChronology.getInstance(timeZone);
        final Object value = originArg.eval(bindings).value();
        if (value instanceof String && NullHandling.isNullOrEquivalent((String) value)) {
            // We get a blank string here, when sql compatible null handling is enabled
            // and expression contains empty string for for origin
            // e.g timestamp_floor(\"__time\",'PT1M','','UTC')
            origin = null;
        } else {
            origin = value != null ? new DateTime(value, chronology) : null;
        }
    }

    return new PeriodGranularity(period, origin, timeZone);
}