Example usage for org.joda.time DateTimeZone getOffset

List of usage examples for org.joda.time DateTimeZone getOffset

Introduction

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

Prototype

public final int getOffset(ReadableInstant instant) 

Source Link

Document

Gets the millisecond offset to add to UTC to get local time.

Usage

From source file:org.jruby.ext.date.RubyDateTime.java

License:LGPL

/**
 # Create a new DateTime object representing the current time.
 #
 # +sg+ specifies the Day of Calendar Reform.
 **///from   w w  w  . j  a v a  2 s  .  c om

@JRubyMethod(meta = true)
public static RubyDateTime now(ThreadContext context, IRubyObject self) { // sg=ITALY
    final DateTimeZone zone = RubyTime.getLocalTimeZone(context.runtime);
    if (zone == DateTimeZone.UTC) {
        return new RubyDateTime(context.runtime, (RubyClass) self, new DateTime(CHRONO_ITALY_UTC), 0);
    }
    final DateTime dt = new DateTime(GJChronology.getInstance(zone));
    final int off = zone.getOffset(dt.getMillis()) / 1000;
    return new RubyDateTime(context.runtime, (RubyClass) self, dt, off, ITALY);
}

From source file:org.jruby.ext.date.RubyDateTime.java

License:LGPL

@JRubyMethod(meta = true)
public static RubyDateTime now(ThreadContext context, IRubyObject self, IRubyObject sg) {
    final long start = val2sg(context, sg);
    final DateTimeZone zone = RubyTime.getLocalTimeZone(context.runtime);
    final DateTime dt = new DateTime(getChronology(context, start, zone));
    final int off = zone.getOffset(dt.getMillis()) / 1000;
    return new RubyDateTime(context.runtime, (RubyClass) self, dt, off, start);
}

From source file:org.jruby.RubyTime.java

License:LGPL

private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt, boolean utcOffset) {
    Ruby runtime = recv.getRuntime();/*from   w  w w.  ja  v a 2 s .  co  m*/
    int len = ARG_SIZE;
    boolean isDst = false;
    boolean setTzRelative = false;
    long nanos = 0;

    DateTimeZone dtz;
    if (gmt) {
        dtz = DateTimeZone.UTC;
    } else if (args.length == 10 && args[9] instanceof RubyString) {
        if (utcOffset) {
            dtz = getTimeZoneFromUtcOffset(runtime, args[9]);
            setTzRelative = true;
        } else {
            dtz = getTimeZoneFromString(runtime, args[9].toString());
        }
    } else if (args.length == 10 && args[9].respondsTo("to_int")) {
        IRubyObject offsetInt = args[9].callMethod(runtime.getCurrentContext(), "to_int");
        dtz = getTimeZone(runtime, ((RubyNumeric) offsetInt).getLongValue());
    } else {
        dtz = getLocalTimeZone(runtime);
    }

    if (args.length == 10) {
        if (args[8] instanceof RubyBoolean)
            isDst = args[8].isTrue();

        args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil() };
    } else {
        // MRI accepts additional wday argument which appears to be ignored.
        len = args.length;

        if (len < ARG_SIZE) {
            IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
            System.arraycopy(args, 0, newArgs, 0, args.length);
            for (int i = len; i < ARG_SIZE; i++) {
                newArgs[i] = runtime.getNil();
            }
            args = newArgs;
            len = ARG_SIZE;
        }
    }

    if (args[0] instanceof RubyString) {
        args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
    }

    int year = (int) RubyNumeric.num2long(args[0]);
    int month = 1;

    if (len > 1) {
        if (!args[1].isNil()) {
            IRubyObject tmp = args[1].checkStringType();
            if (!tmp.isNil()) {
                String monthString = tmp.toString().toLowerCase();
                Integer monthInt = MONTHS_MAP.get(monthString);

                if (monthInt != null) {
                    month = monthInt;
                } else {
                    try {
                        month = Integer.parseInt(monthString);
                    } catch (NumberFormatException nfExcptn) {
                        throw runtime.newArgumentError("Argument out of range.");
                    }
                }
            } else {
                month = (int) RubyNumeric.num2long(args[1]);
            }
        }
        if (1 > month || month > 12) {
            throw runtime.newArgumentError("Argument out of range: for month: " + month);
        }
    }

    int[] int_args = { 1, 0, 0, 0, 0, 0 };

    for (int i = 0; int_args.length >= i + 2; i++) {
        if (!args[i + 2].isNil()) {
            if (!(args[i + 2] instanceof RubyNumeric)) {
                if (args[i + 2].respondsTo("to_int")) {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_int");
                } else {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_i");
                }
            }

            int_args[i] = RubyNumeric.num2int(args[i + 2]);
        }
    }

    // Validate the times
    // Complying with MRI behavior makes it a little bit complicated. Logic copied from:
    // https://github.com/ruby/ruby/blob/trunk/time.c#L2609
    if ((int_args[0] < 1 || int_args[0] > 31) || (int_args[1] < 0 || int_args[1] > 24)
            || (int_args[1] == 24 && (int_args[2] > 0 || int_args[3] > 0))
            || (int_args[2] < 0 || int_args[2] > 59) || (int_args[3] < 0 || int_args[3] > 60)) {
        throw runtime.newArgumentError("argument out of range.");
    }

    DateTime dt;
    // set up with min values and then add to allow rolling over
    try {
        dt = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);

        dt = dt.plusMonths(month - 1).plusDays(int_args[0] - 1).plusHours(int_args[1]).plusMinutes(int_args[2])
                .plusSeconds(int_args[3]);

        // 1.9 will observe fractional seconds *if* not given usec
        if (!args[5].isNil() && args[6].isNil()) {
            double secs = RubyFloat.num2dbl(args[5]);
            int int_millis = (int) (secs * 1000) % 1000;
            dt = dt.plusMillis(int_millis);
            nanos = ((long) (secs * 1000000000) % 1000000);
        }

        dt = dt.withZoneRetainFields(dtz);

        // If we're at a DST boundary, we need to choose the correct side of the boundary
        if (isDst) {
            final DateTime beforeDstBoundary = dt.withEarlierOffsetAtOverlap();
            final DateTime afterDstBoundary = dt.withLaterOffsetAtOverlap();

            final int offsetBeforeBoundary = dtz.getOffset(beforeDstBoundary);
            final int offsetAfterBoundary = dtz.getOffset(afterDstBoundary);

            // If the time is during DST, we need to pick the time with the highest offset
            dt = offsetBeforeBoundary > offsetAfterBoundary ? beforeDstBoundary : afterDstBoundary;
        }
    } catch (org.joda.time.IllegalFieldValueException e) {
        throw runtime.newArgumentError("time out of range");
    }

    RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
    // Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
    if (args.length != 8 && !args[6].isNil()) {
        boolean fractionalUSecGiven = args[6] instanceof RubyFloat || args[6] instanceof RubyRational;

        if (fractionalUSecGiven) {
            double micros = RubyNumeric.num2dbl(args[6]);
            time.dt = dt.withMillis(dt.getMillis() + (long) (micros / 1000));
            nanos = ((long) (micros * 1000) % 1000000);
        } else {
            int usec = int_args[4] % 1000;
            int msec = int_args[4] / 1000;

            if (int_args[4] < 0) {
                msec -= 1;
                usec += 1000;
            }
            time.dt = dt.withMillis(dt.getMillis() + msec);
            time.setUSec(usec);
        }
    }

    if (nanos != 0)
        time.setNSec(nanos);

    time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
    time.setIsTzRelative(setTzRelative);
    return time;
}

From source file:org.killbill.billing.util.account.AccountDateTimeUtils.java

License:Apache License

public static DateTimeZone getFixedOffsetTimeZone(final DateTimeZone referenceDateTimeZone,
        final Entity account) {
    final DateTime referenceDateTime = getReferenceDateTime(account);

    // Check if DST was in effect at the reference date time
    final boolean shouldUseDST = !referenceDateTimeZone.isStandardOffset(referenceDateTime.getMillis());
    if (shouldUseDST) {
        return DateTimeZone.forOffsetMillis(referenceDateTimeZone.getOffset(referenceDateTime.getMillis()));
    } else {//w w w. ja  v  a2s . c o  m
        return DateTimeZone
                .forOffsetMillis(referenceDateTimeZone.getStandardOffset(referenceDateTime.getMillis()));
    }
}

From source file:org.killbill.clock.ClockUtil.java

License:Apache License

/**
 * The method will convert the provided LocalDate into an instant (DateTime).
 * The conversion will use a reference time that should be interpreted from a UTC standpoint.
 *
 * The the provided LocalDate overlaps with the present, the current point in time is returned (to make sure we don't
 * end up with future instant)./*from   w  w w .  j  a  v  a 2s  .c  o m*/
 *
 * If not, we use both the provide LocalDate and LocalTime to return the DateTime in UTC
 *
 * @param inputDateInTargetTimeZone The input LocalDate as interpreted in the specified targetTimeZone
 * @param inputTimeInUTCTimeZone    The referenceTime in UTC
 * @param targetTimeZone            The target timeZone
 * @param clock                     The current clock
 * @return
 */
public static DateTime computeDateTimeWithUTCReferenceTime(final LocalDate inputDateInTargetTimeZone,
        final LocalTime inputTimeInUTCTimeZone, final DateTimeZone targetTimeZone, final Clock clock) {

    final Interval interval = inputDateInTargetTimeZone.toInterval(targetTimeZone);
    // If the input date overlaps with the present, we return NOW.
    if (interval.contains(clock.getUTCNow())) {
        return clock.getUTCNow();
    }
    // If not, we convert the inputTimeInUTCTimeZone -> inputTimeInTargetTimeZone, compute the resulting DateTime in targetTimeZone, and convert into a UTC DateTime:
    final LocalTime inputTimeInTargetTimeZone = inputTimeInUTCTimeZone
            .plusMillis(targetTimeZone.getOffset(clock.getUTCNow()));
    final DateTime resultInTargetTimeZone = new DateTime(inputDateInTargetTimeZone.getYear(),
            inputDateInTargetTimeZone.getMonthOfYear(), inputDateInTargetTimeZone.getDayOfMonth(),
            inputTimeInTargetTimeZone.getHourOfDay(), inputTimeInTargetTimeZone.getMinuteOfHour(),
            inputTimeInTargetTimeZone.getSecondOfMinute(), targetTimeZone);
    return resultInTargetTimeZone.toDateTime(DateTimeZone.UTC);
}

From source file:org.nodatime.tzvalidate.JodaDump.java

License:Open Source License

@Override
public ZoneTransitions getTransitions(String id, int fromYear, int toYear) {
    DateTimeZone zone = zones.get(id);
    // Note that the ID we fetched isn't always the same as DateTimeZone.getID()
    DateTimeFormatter nameFormatter = DateTimeFormat.forPattern("zz").withZone(zone);

    Instant start = new DateTime(fromYear, 1, 1, 0, 0, DateTimeZone.UTC).toInstant();
    Instant end = new DateTime(toYear, 1, 1, 0, 0, DateTimeZone.UTC).toInstant();
    ZoneTransitions transitions = new ZoneTransitions(id);
    long now = start.getMillis();
    transitions.addTransition(null, zone.getOffset(now), !zone.isStandardOffset(now), nameFormatter.print(now));

    now = zone.nextTransition(now);/* w  w w  .  ja va2  s.  c  om*/
    if (now == start.getMillis()) {
        return transitions;
    }
    while (now < end.getMillis()) {
        transitions.addTransition(new Date(now), zone.getOffset(now), !zone.isStandardOffset(now),
                nameFormatter.print(now));
        long next = zone.nextTransition(now);
        if (next <= now) {
            break;
        }
        now = next;
    }
    return transitions;
}

From source file:org.teavm.classlib.impl.tz.ZoneInfoCompiler.java

License:Apache License

/**
 * @return false if error.// w w w  .j a v  a 2s  . c  o m
 */
static boolean test(String id, DateTimeZone tz) {
    if (!id.equals(tz.getID())) {
        return true;
    }

    // Test to ensure that reported transitions are not duplicated.

    long millis = ISOChronology.getInstanceUTC().year().set(0, 1850);
    long end = ISOChronology.getInstanceUTC().year().set(0, 2050);

    int offset = tz.getOffset(millis);

    List<Long> transitions = new ArrayList<>();

    while (true) {
        long next = tz.nextTransition(millis);
        if (next == millis || next > end) {
            break;
        }

        millis = next;

        int nextOffset = tz.getOffset(millis);

        if (offset == nextOffset) {
            System.out.println(
                    "*d* Error in " + tz.getID() + " " + new DateTime(millis, ISOChronology.getInstanceUTC()));
            return false;
        }

        transitions.add(Long.valueOf(millis));

        offset = nextOffset;
    }

    // Now verify that reverse transitions match up.

    millis = ISOChronology.getInstanceUTC().year().set(0, 2050);
    end = ISOChronology.getInstanceUTC().year().set(0, 1850);

    for (int i = transitions.size(); --i >= 0;) {
        long prev = tz.previousTransition(millis);
        if (prev == millis || prev < end) {
            break;
        }

        millis = prev;

        long trans = transitions.get(i).longValue();

        if (trans - 1 != millis) {
            System.out.println(
                    "*r* Error in " + tz.getID() + " " + new DateTime(millis, ISOChronology.getInstanceUTC())
                            + " != " + new DateTime(trans - 1, ISOChronology.getInstanceUTC()));

            return false;
        }
    }

    return true;
}

From source file:org.thelq.pircbotx.commands.NewYearsCommand.java

License:Open Source License

public static String getUTCOffset(DateTimeZone tz) {
    long millis = System.currentTimeMillis();
    while (tz.getOffset(millis) != tz.getStandardOffset(millis)) {
        long next = tz.nextTransition(millis);
        if (next == millis)
            break;
        millis = next;/*from  w  w  w  .j a  va  2  s .c o  m*/
    }
    return "UTC" + FORMATTER_TZOFFSET.withZone(tz).print(millis);
}

From source file:org.unitime.timetable.server.ServerTimeZoneBackend.java

License:Open Source License

@Override
public ServerTimeZoneResponse execute(ServerTimeZoneRequest request, SessionContext context) {
    Date first = null, last = null;
    for (Session session : SessionDAO.getInstance().findAll()) {
        if (first == null || first.after(session.getEventBeginDate()))
            first = session.getEventBeginDate();
        if (last == null || last.before(session.getEventEndDate()))
            last = session.getEventEndDate();
    }//from  www. java2  s  .c om
    DateTimeZone zone = DateTimeZone.getDefault();
    int offsetInMinutes = zone.getOffset(first.getTime()) / 60000;
    ServerTimeZoneResponse ret = new ServerTimeZoneResponse();
    ret.setId(zone.getID());
    ret.addName(zone.getName(new Date().getTime()));
    ret.setTimeZoneOffsetInMinutes(offsetInMinutes);
    long time = first.getTime();
    long transition;
    while (time != (transition = zone.nextTransition(time)) && time < last.getTime()) {
        int adjustment = (zone.getOffset(transition) / 60000) - offsetInMinutes;
        ret.addTransition((int) (transition / 3600000), adjustment);
        time = transition;
    }
    return ret;
}

From source file:org.whole.lang.xsd.parsers.SchemaDataTypeParsers.java

License:Open Source License

private static DateTimeZone validate(DateTimeZone zone) {
    int zoneMillis = zone.getOffset(0L);
    if (zoneMillis > TZ_UPPER || zoneMillis < TZ_LOWER)
        throw new IllegalArgumentException("bad time zone format");
    return zone;// www  . j a  va  2  s. c o  m
}