Java Code Examples for org.joda.time.DateTimeZone#getOffset()

The following examples show how to use org.joda.time.DateTimeZone#getOffset() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DateTimeFunctions.java    From presto with Apache License 2.0 6 votes vote down vote up
private static long timeAtTimeZone(ConnectorSession session, long timeWithTimeZone, TimeZoneKey timeZoneKey)
{
    DateTimeZone sourceTimeZone = getDateTimeZone(unpackZoneKey(timeWithTimeZone));
    DateTimeZone targetTimeZone = getDateTimeZone(timeZoneKey);
    long millis = unpackMillisUtc(timeWithTimeZone);

    // STEP 1. Calculate source UTC millis in session start
    millis += valueToSessionTimeZoneOffsetDiff(session.getStart().toEpochMilli(), sourceTimeZone);

    // STEP 2. Calculate target UTC millis in 1970
    millis -= valueToSessionTimeZoneOffsetDiff(session.getStart().toEpochMilli(), targetTimeZone);

    // STEP 3. Make sure that value + offset is in 0 - 23:59:59.999
    long localMillis = millis + targetTimeZone.getOffset(0);
    // Loops up to 2 times in total
    while (localMillis > TimeUnit.DAYS.toMillis(1)) {
        millis -= TimeUnit.DAYS.toMillis(1);
        localMillis -= TimeUnit.DAYS.toMillis(1);
    }
    while (localMillis < 0) {
        millis += TimeUnit.DAYS.toMillis(1);
        localMillis += TimeUnit.DAYS.toMillis(1);
    }

    return packDateTimeWithZone(millis, timeZoneKey);
}
 
Example 2
Source File: ServerTimeZoneBackend.java    From unitime with Apache License 2.0 6 votes vote down vote up
@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();
	}
	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;
}
 
Example 3
Source File: Time_7_DateTimeFormatter_t.java    From coming with MIT License 6 votes vote down vote up
private void printTo(StringBuffer buf, long instant, Chronology chrono) {
    DateTimePrinter printer = requirePrinter();
    chrono = selectChronology(chrono);
    // Shift instant into local time (UTC) to avoid excessive offset
    // calculations when printing multiple fields in a composite printer.
    DateTimeZone zone = chrono.getZone();
    int offset = zone.getOffset(instant);
    long adjustedInstant = instant + offset;
    if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) {
        // Time zone offset overflow, so revert to UTC.
        zone = DateTimeZone.UTC;
        offset = 0;
        adjustedInstant = instant;
    }
    printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale);
}
 
Example 4
Source File: Time_16_DateTimeFormatter_s.java    From coming with MIT License 6 votes vote down vote up
private void printTo(Writer buf, long instant, Chronology chrono) throws IOException {
    DateTimePrinter printer = requirePrinter();
    chrono = selectChronology(chrono);
    // Shift instant into local time (UTC) to avoid excessive offset
    // calculations when printing multiple fields in a composite printer.
    DateTimeZone zone = chrono.getZone();
    int offset = zone.getOffset(instant);
    long adjustedInstant = instant + offset;
    if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) {
        // Time zone offset overflow, so revert to UTC.
        zone = DateTimeZone.UTC;
        offset = 0;
        adjustedInstant = instant;
    }
    printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale);
}
 
Example 5
Source File: Time_16_DateTimeFormatter_s.java    From coming with MIT License 6 votes vote down vote up
private void printTo(StringBuffer buf, long instant, Chronology chrono) {
    DateTimePrinter printer = requirePrinter();
    chrono = selectChronology(chrono);
    // Shift instant into local time (UTC) to avoid excessive offset
    // calculations when printing multiple fields in a composite printer.
    DateTimeZone zone = chrono.getZone();
    int offset = zone.getOffset(instant);
    long adjustedInstant = instant + offset;
    if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) {
        // Time zone offset overflow, so revert to UTC.
        zone = DateTimeZone.UTC;
        offset = 0;
        adjustedInstant = instant;
    }
    printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale);
}
 
Example 6
Source File: DateTimeFormatter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void printTo(StringBuffer buf, long instant, Chronology chrono) {
    DateTimePrinter printer = requirePrinter();
    chrono = selectChronology(chrono);
    // Shift instant into local time (UTC) to avoid excessive offset
    // calculations when printing multiple fields in a composite printer.
    DateTimeZone zone = chrono.getZone();
    int offset = zone.getOffset(instant);
    long adjustedInstant = instant + offset;
    if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) {
        // Time zone offset overflow, so revert to UTC.
        zone = DateTimeZone.UTC;
        offset = 0;
        adjustedInstant = instant;
    }
    printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale);
}
 
Example 7
Source File: DateTimeFormatter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void printTo(Writer buf, long instant, Chronology chrono) throws IOException {
    DateTimePrinter printer = requirePrinter();
    chrono = selectChronology(chrono);
    // Shift instant into local time (UTC) to avoid excessive offset
    // calculations when printing multiple fields in a composite printer.
    DateTimeZone zone = chrono.getZone();
    int offset = zone.getOffset(instant);
    long adjustedInstant = instant + offset;
    if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) {
        // Time zone offset overflow, so revert to UTC.
        zone = DateTimeZone.UTC;
        offset = 0;
        adjustedInstant = instant;
    }
    printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale);
}
 
Example 8
Source File: Cardumen_0073_s.java    From coming with MIT License 6 votes vote down vote up
private void printTo(StringBuffer buf, long instant, Chronology chrono) {
    DateTimePrinter printer = requirePrinter();
    chrono = selectChronology(chrono);
    // Shift instant into local time (UTC) to avoid excessive offset
    // calculations when printing multiple fields in a composite printer.
    DateTimeZone zone = chrono.getZone();
    int offset = zone.getOffset(instant);
    long adjustedInstant = instant + offset;
    if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) {
        // Time zone offset overflow, so revert to UTC.
        zone = DateTimeZone.UTC;
        offset = 0;
        adjustedInstant = instant;
    }
    printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale);
}
 
Example 9
Source File: DateTimeFormatter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void printTo(StringBuffer buf, long instant, Chronology chrono) {
    DateTimePrinter printer = requirePrinter();
    chrono = selectChronology(chrono);
    // Shift instant into local time (UTC) to avoid excessive offset
    // calculations when printing multiple fields in a composite printer.
    DateTimeZone zone = chrono.getZone();
    int offset = zone.getOffset(instant);
    long adjustedInstant = instant + offset;
    if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) {
        // Time zone offset overflow, so revert to UTC.
        zone = DateTimeZone.UTC;
        offset = 0;
        adjustedInstant = instant;
    }
    printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale);
}
 
Example 10
Source File: Time_26_ZonedChronology_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param instant instant from 1970-01-01T00:00:00 local time
 * @return instant from 1970-01-01T00:00:00Z
 */
private long localToUTC(long instant) {
    DateTimeZone zone = getZone();
    int offset = zone.getOffsetFromLocal(instant);
    instant -= offset;
    if (offset != zone.getOffset(instant)) {
        throw new IllegalArgumentException
            ("Illegal instant due to time zone offset transition: " +
                DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS").print(new Instant(instant)));
    }
    return instant;
}
 
Example 11
Source File: TimeZoneInfo.java    From es6draft with MIT License 5 votes vote down vote up
@Override
public String getDisplayName(TimeZone tz, long date) {
    DateTimeZone timeZone = toDateTimeZone(tz);
    if (IGNORE_LOCAL_BEFORE_EPOCH) {
        if (date < EPOCH) {
            date = toFirstDateWithNormalizedTime(timeZone, date);
        }
    } else if (IGNORE_LOCAL) {
        if (date <= LAST_LOCAL_TRANSITION) {
            date = toFirstDateWithNormalizedTime(timeZone, date);
        }
    } else if (IGNORE_LMT) {
        if (date <= LAST_LMT_TRANSITION) {
            date = toFirstDateAfterLocalMeanTime(timeZone, date);
        }
    }
    String displayName = timeZone.getNameKey(date);
    if (displayName != null) {
        return displayName;
    }
    boolean daylightSavings = !timeZone.isStandardOffset(date);
    if (!daylightSavings
            && timeZone.getOffset(date) != timeZone.getStandardOffset(System.currentTimeMillis())) {
        daylightSavings = timeZone.nextTransition(date) != date;
    }
    return tz.getDisplayName(daylightSavings, TimeZone.SHORT, Locale.US);
}
 
Example 12
Source File: ZonedChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param localInstant  the instant from 1970-01-01T00:00:00 local time
 * @return the instant from 1970-01-01T00:00:00Z
 */
private long localToUTC(long localInstant) {
    DateTimeZone zone = getZone();
    int offset = zone.getOffsetFromLocal(localInstant);
    localInstant -= offset;
    if (offset != zone.getOffset(localInstant)) {
        throw new IllegalInstantException(localInstant, zone.getID());
    }
    return localInstant;
}
 
Example 13
Source File: ZonedChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param localInstant  the instant from 1970-01-01T00:00:00 local time
 * @return the instant from 1970-01-01T00:00:00Z
 */
private long localToUTC(long localInstant) {
    DateTimeZone zone = getZone();
    int offset = zone.getOffsetFromLocal(localInstant);
    localInstant -= offset;
    if (offset != zone.getOffset(localInstant)) {
        throw new IllegalInstantException(localInstant, zone.getID());
    }
    return localInstant;
}
 
Example 14
Source File: ConvertTimezoneFunction.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) {
    if (!children.get(0).evaluate(tuple, ptr)) {
        return false;
    }
    if (ptr.getLength() == 0) {
        return true;
    }
    long date = PDate.INSTANCE.getCodec().decodeLong(ptr, children.get(0).getSortOrder());

    if (!children.get(1).evaluate(tuple, ptr)) {
        return false;
    }
    if (ptr.getLength() == 0) {
        return true;
    }
    DateTimeZone timezoneFrom = JodaTimezoneCache.getInstance(ptr);

    if (!children.get(2).evaluate(tuple, ptr)) {
        return false;
    }
    if (ptr.getLength() == 0) {
        return true;
    }
    DateTimeZone timezoneTo = JodaTimezoneCache.getInstance(ptr);

    long convertedDate = date - timezoneFrom.getOffset(date) + timezoneTo.getOffset(date);
    byte[] outBytes = new byte[8];
    PDate.INSTANCE.getCodec().encodeLong(convertedDate, outBytes, 0);
    ptr.set(outBytes);
    return true;
}
 
Example 15
Source File: CommonUtils.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public static String getUTCOffset(DateTimeZone zone) {
    int offset = zone.getOffset(DateTime.now());

    long hours = TimeUnit.MILLISECONDS.toHours(offset);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(offset - TimeUnit.HOURS.toMillis(hours));

    return String.format("UTC%s%d:%02d", hours > 0 ? '+' : '-', hours, minutes);
}
 
Example 16
Source File: PluginDateUtils.java    From template-compiler with Apache License 2.0 4 votes vote down vote up
public static void humanizeDate(long instantMs, long baseMs, String tzId, boolean showSeconds, StringBuilder buf) {
  DateTimeZone timeZone = DateTimeZone.forID(tzId);
  int offset = timeZone.getOffset(instantMs);
  Duration delta = new Duration(baseMs - instantMs + offset);

  int days = (int)delta.getStandardDays();
  int years = (int)Math.floor(days / 365.0);
  if (years > 0) {
    humanizeDatePlural(years, DatePartType.YEAR, buf);
    return;
  }
  int months = (int)Math.floor(days / 30.0);
  if (months > 0) {
    humanizeDatePlural(months, DatePartType.MONTH, buf);
    return;
  }
  int weeks = (int)Math.floor(days / 7.0);
  if (weeks > 0) {
    humanizeDatePlural(weeks, DatePartType.WEEK, buf);
    return;
  }
  if (days > 0) {
    humanizeDatePlural(days, DatePartType.DAY, buf);
    return;
  }
  int hours = (int)delta.getStandardHours();
  if (hours > 0) {
    humanizeDatePlural(hours, DatePartType.HOUR, buf);
    return;
  }
  int mins = (int)delta.getStandardMinutes();
  if (mins > 0) {
    humanizeDatePlural(mins, DatePartType.MINUTE, buf);
    return;
  }
  int secs = (int)delta.getStandardSeconds();
  if (showSeconds) {
    humanizeDatePlural(secs, DatePartType.SECOND, buf);
    return;
  }
  buf.append("less than a minute ago");
}
 
Example 17
Source File: ZoneInfoCompiler.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return false if error.
 */
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);
    String key = tz.getNameKey(millis);

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

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

        millis = next;

        int nextOffset = tz.getOffset(millis);
        String nextKey = tz.getNameKey(millis);

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

        if (nextKey == null || (nextKey.length() < 3 && !"??".equals(nextKey))) {
            System.out.println("*s* Error in " + tz.getID() + " "
                               + new DateTime(millis,
                                              ISOChronology.getInstanceUTC())
                               + ", nameKey=" + nextKey);
            return false;
        }

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

        offset = nextOffset;
        key = nextKey;
    }

    // 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;
}
 
Example 18
Source File: ZoneInfoCompiler.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return false if error.
 */
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);
    String key = tz.getNameKey(millis);

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

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

        millis = next;

        int nextOffset = tz.getOffset(millis);
        String nextKey = tz.getNameKey(millis);

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

        if (nextKey == null || (nextKey.length() < 3 && !"??".equals(nextKey))) {
            System.out.println("*s* Error in " + tz.getID() + " "
                               + new DateTime(millis,
                                              ISOChronology.getInstanceUTC())
                               + ", nameKey=" + nextKey);
            return false;
        }

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

        offset = nextOffset;
        key = nextKey;
    }

    // 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;
}
 
Example 19
Source File: DateTimeFunctions.java    From presto with Apache License 2.0 4 votes vote down vote up
public static long valueToSessionTimeZoneOffsetDiff(long epochMillis, DateTimeZone timeZone)
{
    return timeZone.getOffset(0) - timeZone.getOffset(epochMillis);
}
 
Example 20
Source File: ServerValueEncoder.java    From sql-layer with GNU Affero General Public License v3.0 2 votes vote down vote up
/** Adjust milliseconds since 1970-01-01 00:00:00-UTC to seconds since
 * 2000-01-01 00:00:00 timezoneless. A conversion from local time
 * to UTC involves an offset that varies for Summer time. A
 * conversion from local time to timezoneless just removes the
 * zone as though all days were the same length.
 */
private static long seconds2000NoTZ(long millis) {
    DateTimeZone dtz = DateTimeZone.getDefault();
    millis += dtz.getOffset(millis);
    return millis / 1000 - 946684800; // 2000-01-01 00:00:00-UTC.
}