java.util.TimeZone#getOffset ( )源码实例Demo

下面列出了java.util.TimeZone#getOffset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hottub   文件: DatatypeConverterImpl.java
/** 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);
}
 
源代码2 项目: qpid-broker-j   文件: TimeZoneServlet.java
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;
}
 
源代码3 项目: trekarta   文件: SunriseSunset.java
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;
}
 
源代码4 项目: FairEmail   文件: INTERNALDATE.java
/**
    * 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();
   }
 
源代码5 项目: NightWatch   文件: PebbleSync.java
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;
}
 
源代码6 项目: android-dev-challenge   文件: SunshineDateUtils.java
/**
 * 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;
}
 
源代码7 项目: openjdk-8-source   文件: DatatypeConverterImpl.java
/** 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);
}
 
源代码8 项目: Bats   文件: SqlFunctions.java
public static long toLong(java.util.Date v, TimeZone timeZone) {
  final long time = v.getTime();
  return time + timeZone.getOffset(time);
}
 
源代码9 项目: calcite   文件: SqlFunctions.java
public static long toLong(java.util.Date v, TimeZone timeZone) {
  final long time = v.getTime();
  return time + timeZone.getOffset(time);
}
 
源代码10 项目: jdk8u60   文件: NativeDate.java
private static double localTime(final double time, final TimeZone tz) {
    return time + tz.getOffset((long) time);
}
 
源代码11 项目: carina   文件: DeviceTimeZone.java
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;
}
 
源代码12 项目: jdk8u_jdk   文件: AbstractCalendar.java
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;
}
 
源代码13 项目: android-dev-challenge   文件: SunshineDateUtils.java
/**
 * 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;
}
 
源代码14 项目: android-dev-challenge   文件: SunshineDateUtils.java
/**
 * 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;
}
 
源代码15 项目: nashorn   文件: NativeDate.java
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;
}
 
源代码16 项目: lams   文件: DateUtil.java
/**
    * 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);
   }
 
源代码17 项目: android-dev-challenge   文件: SunshineDateUtils.java
/**
 * 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;
}
 
源代码18 项目: android-dev-challenge   文件: SunshineDateUtils.java
/**
 * 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;
}
 
源代码19 项目: CodenameOne   文件: SimpleDateFormat.java
/**
 * 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;
}
 
源代码20 项目: android-dev-challenge   文件: SunshineDateUtils.java
/**
 * 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;
}