Java Code Examples for java.util.TimeZone#getOffset()

The following examples show how to use java.util.TimeZone#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: DatatypeConverterImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/** formats time zone specifier. */
private static void formatTimeZone(Calendar cal, StringBuilder buf) {
    TimeZone tz = cal.getTimeZone();

    if (tz == null) {
        return;
    }

    // otherwise print out normally.
    int offset = tz.getOffset(cal.getTime().getTime());

    if (offset == 0) {
        buf.append('Z');
        return;
    }

    if (offset >= 0) {
        buf.append('+');
    } else {
        buf.append('-');
        offset *= -1;
    }

    offset /= 60 * 1000; // offset is in milli-seconds

    formatTwoDigits(offset / 60, buf);
    buf.append(':');
    formatTwoDigits(offset % 60, buf);
}
 
Example 2
Source File: DatatypeConverterImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/** formats time zone specifier. */
private static void formatTimeZone(Calendar cal, StringBuilder buf) {
    TimeZone tz = cal.getTimeZone();

    if (tz == null) {
        return;
    }

    // otherwise print out normally.
    int offset = tz.getOffset(cal.getTime().getTime());

    if (offset == 0) {
        buf.append('Z');
        return;
    }

    if (offset >= 0) {
        buf.append('+');
    } else {
        buf.append('-');
        offset *= -1;
    }

    offset /= 60 * 1000; // offset is in milli-seconds

    formatTwoDigits(offset / 60, buf);
    buf.append(':');
    formatTwoDigits(offset % 60, buf);
}
 
Example 3
Source File: TimeZoneServlet.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public List<TimeZoneDetails> getTimeZones()
{
    List<TimeZoneDetails> timeZoneDetails = new ArrayList<TimeZoneDetails>();
    String[] ids = TimeZone.getAvailableIDs();
    long currentTime = System.currentTimeMillis();
    Date currentDate = new Date(currentTime);
    for (String id : ids)
    {
        int cityPos = id.indexOf("/");
        if (cityPos > 0 && cityPos < id.length() - 1)
        {
            String region = id.substring(0, cityPos);
            for (int i = 0; i < TIMEZONE_REGIONS.length; i++)
            {
                if (region.equals(TIMEZONE_REGIONS[i]))
                {
                    TimeZone tz = TimeZone.getTimeZone(id);
                    int offset = tz.getOffset(currentTime)/60000;
                    String city = id.substring(cityPos + 1).replace('_', ' ');
                    timeZoneDetails.add(new TimeZoneDetails(id, tz.getDisplayName(tz.inDaylightTime(currentDate), TimeZone.SHORT), offset, city, region));
                    break;
                }
            }
        }
    }
    return timeZoneDetails;
}
 
Example 4
Source File: SunriseSunset.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
public void setLocation(double latitude, double longitude) {
    String timeZoneId = TimezoneMapper.latLngToTimezoneString(latitude, longitude);
    TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
    tzOffset = timeZone.getOffset(calendar.getTimeInMillis()) * 1d / 3600000;

    latRad = Math.toRadians(latitude);
    // 2a. convert the longitude to hour value
    lngHour = longitude / 15;
}
 
Example 5
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 5 votes vote down vote up
/**
 * This method will return the local time midnight for the provided normalized UTC date.
 *
 * @param normalizedUtcDate UTC time at midnight for a given date. This number comes from the
 *                          database
 *
 * @return The local date corresponding to the given normalized UTC date
 */
private static long getLocalMidnightFromNormalizedUtcDate(long normalizedUtcDate) {
    /* The timeZone object will provide us the current user's time zone offset */
    TimeZone timeZone = TimeZone.getDefault();
    /*
     * This offset, in milliseconds, when added to a UTC date time, will produce the local
     * time.
     */
    long gmtOffset = timeZone.getOffset(normalizedUtcDate);
    long localMidnightMillis = normalizedUtcDate - gmtOffset;
    return localMidnightMillis;
}
 
Example 6
Source File: INTERNALDATE.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
/**
    * Format given Date object into INTERNALDATE string
    *
    * @param	d	the Date
    * @return		INTERNALDATE string
    */
   public static String format(Date d) {
/*
 * SimpleDateFormat objects aren't thread safe, so rather
 * than create a separate such object for each request,
 * we create one object and synchronize its use here
 * so that only one thread is using it at a time.  This
 * trades off some potential concurrency for speed in the
 * common case.
 *
 * This method is only used when formatting the date in a
 * message that's being appended to a folder.
 */
StringBuffer sb = new StringBuffer();
synchronized (df) {
    df.format(d, sb, new FieldPosition(0));
}

// compute timezone offset string
TimeZone tz = TimeZone.getDefault();
int offset = tz.getOffset(d.getTime());	// get offset from GMT
int rawOffsetInMins = offset / 60 / 1000; // offset from GMT in mins
if (rawOffsetInMins < 0) {
    sb.append('-');
    rawOffsetInMins = (-rawOffsetInMins);
} else
    sb.append('+');

int offsetInHrs = rawOffsetInMins / 60;
int offsetInMins = rawOffsetInMins % 60;

sb.append(Character.forDigit((offsetInHrs/10), 10));
sb.append(Character.forDigit((offsetInHrs%10), 10));
sb.append(Character.forDigit((offsetInMins/10), 10));
sb.append(Character.forDigit((offsetInMins%10), 10));

return sb.toString();
   }
 
Example 7
Source File: PebbleSync.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
public PebbleDictionary buildDictionary() {
    PebbleDictionary dictionary = new PebbleDictionary();
    TimeZone tz = TimeZone.getDefault();
    Date now = new Date();
    int offsetFromUTC = tz.getOffset(now.getTime());
    Log.v(TAG, "buildDictionary: slopeOrdinal-" + slopeOrdinal() + " bgReading-" + bgReading() + " now-"+ (int) now.getTime()/1000 + " bgTime-" + (int) (mBgReading.datetime / 1000) + " phoneTime-" + (int) (new Date().getTime() / 1000) + " bgDelta-" + bgDelta());
    dictionary.addString(ICON_KEY, slopeOrdinal());
    dictionary.addString(BG_KEY, bgReading());
    dictionary.addUint32(RECORD_TIME_KEY, (int) (((mBgReading.datetime + offsetFromUTC) / 1000)));
    dictionary.addUint32(PHONE_TIME_KEY, (int) ((new Date().getTime() + offsetFromUTC) / 1000));
    dictionary.addString(BG_DELTA_KEY, bgDelta());
    dictionary.addString(UPLOADER_BATTERY_KEY, phoneBattery());
    dictionary.addString(NAME_KEY, "Phone");
    return dictionary;
}
 
Example 8
Source File: DeviceTimeZone.java    From carina with Apache License 2.0 4 votes vote down vote up
public static int compare(TimeZone tz1, TimeZone tz2) {
    Calendar cal = GregorianCalendar.getInstance(tz1);
    long date = cal.getTimeInMillis();
    return (tz2.getOffset(date) - tz1.getOffset(date)) / 3600000;
}
 
Example 9
Source File: NativeDate.java    From nashorn with GNU General Public License v2.0 4 votes vote down vote up
private static String toStringImpl(final Object self, final int format) {
    final NativeDate nd = getNativeDate(self);

    if (nd != null && nd.isValidDate()) {
        final StringBuilder sb = new StringBuilder(40);
        final double t = nd.getLocalTime();

        switch (format) {

            case FORMAT_DATE_TIME:
            case FORMAT_DATE :
            case FORMAT_LOCAL_DATE_TIME:
                // EEE MMM dd yyyy
                sb.append(weekDays[weekDay(t)])
                        .append(' ')
                        .append(months[monthFromTime(t)])
                        .append(' ');
                zeroPad(sb, dayFromTime(t), 2);
                sb.append(' ');
                zeroPad(sb, yearFromTime(t), 4);
                if (format == FORMAT_DATE) {
                    break;
                }
                sb.append(' ');

                //$FALL-THROUGH$
            case FORMAT_TIME:
                final TimeZone tz = nd.getTimeZone();
                final double utcTime = nd.getTime();
                int offset = tz.getOffset((long) utcTime) / 60000;
                final boolean inDaylightTime = offset != tz.getRawOffset() / 60000;
                // Convert minutes to HHmm timezone offset
                offset = (offset / 60) * 100 + offset % 60;

                // HH:mm:ss GMT+HHmm
                zeroPad(sb, hourFromTime(t), 2);
                sb.append(':');
                zeroPad(sb, minFromTime(t), 2);
                sb.append(':');
                zeroPad(sb, secFromTime(t), 2);
                sb.append(" GMT")
                        .append(offset < 0 ? '-' : '+');
                zeroPad(sb, Math.abs(offset), 4);
                sb.append(" (")
                        .append(tz.getDisplayName(inDaylightTime, TimeZone.SHORT, Locale.US))
                        .append(')');
                break;

            case FORMAT_LOCAL_DATE:
                // yyyy-MM-dd
                zeroPad(sb, yearFromTime(t), 4);
                sb.append('-');
                zeroPad(sb, monthFromTime(t) + 1, 2);
                sb.append('-');
                zeroPad(sb, dayFromTime(t), 2);
                break;

            case FORMAT_LOCAL_TIME:
                // HH:mm:ss
                zeroPad(sb, hourFromTime(t), 2);
                sb.append(':');
                zeroPad(sb, minFromTime(t), 2);
                sb.append(':');
                zeroPad(sb, secFromTime(t), 2);
                break;

            default:
                throw new IllegalArgumentException("format: " + format);
        }

        return sb.toString();
    }

    return INVALID_DATE;
}
 
Example 10
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns the number of milliseconds (UTC time) for today's date at midnight in
 * the local time zone. For example, if you live in California and the day is September 20th,
 * 2016 and it is 6:30 PM, it will return 1474329600000. Now, if you plug this number into an
 * Epoch time converter, you may be confused that it tells you this time stamp represents 8:00
 * PM on September 19th local time, rather than September 20th. We're concerned with the GMT
 * date here though, which is correct, stating September 20th, 2016 at midnight.
 *
 * As another example, if you are in Hong Kong and the day is September 20th, 2016 and it is
 * 6:30 PM, this method will return 1474329600000. Again, if you plug this number into an Epoch
 * time converter, you won't get midnight for your local time zone. Just keep in mind that we
 * are just looking at the GMT date here.
 *
 * This method will ALWAYS return the date at midnight (in GMT time) for the time zone you
 * are currently in. In other words, the GMT date will always represent your date.
 *
 * Since UTC / GMT time are the standard for all time zones in the world, we use it to
 * normalize our dates that are stored in the database. When we extract values from the
 * database, we adjust for the current time zone using time zone offsets.
 *
 * @return The number of milliseconds (UTC / GMT) for today's date at midnight in the local
 * time zone
 */
public static long getNormalizedUtcDateForToday() {

    /*
     * This number represents the number of milliseconds that have elapsed since January
     * 1st, 1970 at midnight in the GMT time zone.
     */
    long utcNowMillis = System.currentTimeMillis();

    /*
     * This TimeZone represents the device's current time zone. It provides us with a means
     * of acquiring the offset for local time from a UTC time stamp.
     */
    TimeZone currentTimeZone = TimeZone.getDefault();

    /*
     * The getOffset method returns the number of milliseconds to add to UTC time to get the
     * elapsed time since the epoch for our current time zone. We pass the current UTC time
     * into this method so it can determine changes to account for daylight savings time.
     */
    long gmtOffsetMillis = currentTimeZone.getOffset(utcNowMillis);

    /*
     * UTC time is measured in milliseconds from January 1, 1970 at midnight from the GMT
     * time zone. Depending on your time zone, the time since January 1, 1970 at midnight (GMT)
     * will be greater or smaller. This variable represents the number of milliseconds since
     * January 1, 1970 (GMT) time.
     */
    long timeSinceEpochLocalTimeMillis = utcNowMillis + gmtOffsetMillis;

    /* This method simply converts milliseconds to days, disregarding any fractional days */
    long daysSinceEpochLocal = TimeUnit.MILLISECONDS.toDays(timeSinceEpochLocalTimeMillis);

    /*
     * Finally, we convert back to milliseconds. This time stamp represents today's date at
     * midnight in GMT time. We will need to account for local time zone offsets when
     * extracting this information from the database.
     */
    long normalizedUtcMidnightMillis = TimeUnit.DAYS.toMillis(daysSinceEpochLocal);

    return normalizedUtcMidnightMillis;
}
 
Example 11
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns the number of milliseconds (UTC time) for today's date at midnight in
 * the local time zone. For example, if you live in California and the day is September 20th,
 * 2016 and it is 6:30 PM, it will return 1474329600000. Now, if you plug this number into an
 * Epoch time converter, you may be confused that it tells you this time stamp represents 8:00
 * PM on September 19th local time, rather than September 20th. We're concerned with the GMT
 * date here though, which is correct, stating September 20th, 2016 at midnight.
 *
 * As another example, if you are in Hong Kong and the day is September 20th, 2016 and it is
 * 6:30 PM, this method will return 1474329600000. Again, if you plug this number into an Epoch
 * time converter, you won't get midnight for your local time zone. Just keep in mind that we
 * are just looking at the GMT date here.
 *
 * This method will ALWAYS return the date at midnight (in GMT time) for the time zone you
 * are currently in. In other words, the GMT date will always represent your date.
 *
 * Since UTC / GMT time are the standard for all time zones in the world, we use it to
 * normalize our dates that are stored in the database. When we extract values from the
 * database, we adjust for the current time zone using time zone offsets.
 *
 * @return The number of milliseconds (UTC / GMT) for today's date at midnight in the local
 * time zone
 */
public static long getNormalizedUtcDateForToday() {

    /*
     * This number represents the number of milliseconds that have elapsed since January
     * 1st, 1970 at midnight in the GMT time zone.
     */
    long utcNowMillis = System.currentTimeMillis();

    /*
     * This TimeZone represents the device's current time zone. It provides us with a means
     * of acquiring the offset for local time from a UTC time stamp.
     */
    TimeZone currentTimeZone = TimeZone.getDefault();

    /*
     * The getOffset method returns the number of milliseconds to add to UTC time to get the
     * elapsed time since the epoch for our current time zone. We pass the current UTC time
     * into this method so it can determine changes to account for daylight savings time.
     */
    long gmtOffsetMillis = currentTimeZone.getOffset(utcNowMillis);

    /*
     * UTC time is measured in milliseconds from January 1, 1970 at midnight from the GMT
     * time zone. Depending on your time zone, the time since January 1, 1970 at midnight (GMT)
     * will be greater or smaller. This variable represents the number of milliseconds since
     * January 1, 1970 (GMT) time.
     */
    long timeSinceEpochLocalTimeMillis = utcNowMillis + gmtOffsetMillis;

    /* This method simply converts milliseconds to days, disregarding any fractional days */
    long daysSinceEpochLocal = TimeUnit.MILLISECONDS.toDays(timeSinceEpochLocalTimeMillis);

    /*
     * Finally, we convert back to milliseconds. This time stamp represents today's date at
     * midnight in GMT time. We will need to account for local time zone offsets when
     * extracting this information from the database.
     */
    long normalizedUtcMidnightMillis = TimeUnit.DAYS.toMillis(daysSinceEpochLocal);

    return normalizedUtcMidnightMillis;
}
 
Example 12
Source File: AbstractCalendar.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public CalendarDate getCalendarDate(long millis, CalendarDate date) {
    int ms = 0;             // time of day
    int zoneOffset = 0;
    int saving = 0;
    long days = 0;          // fixed date

    // adjust to local time if `date' has time zone.
    TimeZone zi = date.getZone();
    if (zi != null) {
        int[] offsets = new int[2];
        if (zi instanceof ZoneInfo) {
            zoneOffset = ((ZoneInfo)zi).getOffsets(millis, offsets);
        } else {
            zoneOffset = zi.getOffset(millis);
            offsets[0] = zi.getRawOffset();
            offsets[1] = zoneOffset - offsets[0];
        }

        // We need to calculate the given millis and time zone
        // offset separately for java.util.GregorianCalendar
        // compatibility. (i.e., millis + zoneOffset could cause
        // overflow or underflow, which must be avoided.) Usually
        // days should be 0 and ms is in the range of -13:00 to
        // +14:00. However, we need to deal with extreme cases.
        days = zoneOffset / DAY_IN_MILLIS;
        ms = zoneOffset % DAY_IN_MILLIS;
        saving = offsets[1];
    }
    date.setZoneOffset(zoneOffset);
    date.setDaylightSaving(saving);

    days += millis / DAY_IN_MILLIS;
    ms += (int) (millis % DAY_IN_MILLIS);
    if (ms >= DAY_IN_MILLIS) {
        // at most ms is (DAY_IN_MILLIS - 1) * 2.
        ms -= DAY_IN_MILLIS;
        ++days;
    } else {
        // at most ms is (1 - DAY_IN_MILLIS) * 2. Adding one
        // DAY_IN_MILLIS results in still negative.
        while (ms < 0) {
            ms += DAY_IN_MILLIS;
            --days;
        }
    }

    // convert to fixed date (offset from Jan. 1, 1 (Gregorian))
    days += EPOCH_OFFSET;

    // calculate date fields from the fixed date
    getCalendarDateFromFixedDate(date, days);

    // calculate time fields from the time of day
    setTimeOfDay(date, ms);
    date.setLeapYear(isLeapYear(date));
    date.setNormalized(true);
    return date;
}
 
Example 13
Source File: SqlFunctions.java    From Bats with Apache License 2.0 4 votes vote down vote up
public static long toLong(java.util.Date v, TimeZone timeZone) {
  final long time = v.getTime();
  return time + timeZone.getOffset(time);
}
 
Example 14
Source File: NativeDate.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private static double localTime(final double time, final TimeZone tz) {
    return time + tz.getOffset((long) time);
}
 
Example 15
Source File: SqlFunctions.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static long toLong(java.util.Date v, TimeZone timeZone) {
  final long time = v.getTime();
  return time + timeZone.getOffset(time);
}
 
Example 16
Source File: DateUtil.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
    * Convert from local time to your client (time zone) time.
    *
    * @param targetTimeZone
    *            time zone converting to.
    * @param date
    *            date to convert.
    * @return your time zone date time.
    */
   public static Date convertToTimeZoneFromDefault(TimeZone targetTimeZone, Date date) {
TimeZone defaultTz = TimeZone.getDefault();
Integer rawOffset = defaultTz.getOffset(date.getTime()) - targetTimeZone.getOffset(date.getTime());

return new Date(date.getTime() - rawOffset);
   }
 
Example 17
Source File: SimpleDateFormat.java    From CodenameOne with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Get the offset from GMT for a given timezone.
 * 
 * @param source
 * @param timezone
 * @return
 */
int getOffsetInMinutes(Calendar source, TimeZone timezone) {
	return timezone.getOffset(source.get(ERA), source.get(Calendar.YEAR), source.get(Calendar.MONTH),
			source.get(Calendar.DAY_OF_MONTH), source.get(Calendar.DAY_OF_WEEK), source.get(Calendar.MILLISECOND))
			/ MILLIS_TO_MINUTES;
}
 
Example 18
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 2 votes vote down vote up
/**
 * Since all dates from the database are in UTC, we must convert the given date
 * (in UTC timezone) to the date in the local timezone. Ths function performs that conversion
 * using the TimeZone offset.
 *
 * @param utcDate The UTC datetime to convert to a local datetime, in milliseconds.
 * @return The local date (the UTC datetime - the TimeZone offset) in milliseconds.
 */
public static long getLocalDateFromUTC(long utcDate) {
    TimeZone tz = TimeZone.getDefault();
    long gmtOffset = tz.getOffset(utcDate);
    return utcDate - gmtOffset;
}
 
Example 19
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 2 votes vote down vote up
/**
 * Since all dates from the database are in UTC, we must convert the given date
 * (in UTC timezone) to the date in the local timezone. Ths function performs that conversion
 * using the TimeZone offset.
 *
 * @param utcDate The UTC datetime to convert to a local datetime, in milliseconds.
 * @return The local date (the UTC datetime - the TimeZone offset) in milliseconds.
 */
public static long getLocalDateFromUTC(long utcDate) {
    TimeZone tz = TimeZone.getDefault();
    long gmtOffset = tz.getOffset(utcDate);
    return utcDate - gmtOffset;
}
 
Example 20
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 2 votes vote down vote up
/**
 * This method returns the number of days since the epoch (January 01, 1970, 12:00 Midnight UTC)
 * in UTC time from the current date.
 *
 * @param date A date in milliseconds in local time.
 *
 * @return The number of days in UTC time from the epoch.
 */
public static long getDayNumber(long date) {
    TimeZone tz = TimeZone.getDefault();
    long gmtOffset = tz.getOffset(date);
    return (date + gmtOffset) / DAY_IN_MILLIS;
}