下面列出了java.util.TimeZone#getRawOffset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns true if this zone has the same raw GMT offset value and
* transition table as another zone info. If the specified
* TimeZone object is not a ZoneInfoOld instance, this method returns
* true if the specified TimeZone object has the same raw GMT
* offset value with no daylight saving time.
*
* @param other the ZoneInfoOld object to be compared with
* @return true if the given <code>TimeZone</code> has the same
* GMT offset and transition information; false, otherwise.
*/
public boolean hasSameRules(TimeZone other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (!(other instanceof ZoneInfoOld)) {
if (getRawOffset() != other.getRawOffset()) {
return false;
}
// if both have the same raw offset and neither observes
// DST, they have the same rule.
if ((transitions == null)
&& (useDaylightTime() == false)
&& (other.useDaylightTime() == false)) {
return true;
}
return false;
}
if (getLastRawOffset() != ((ZoneInfoOld)other).getLastRawOffset()) {
return false;
}
return (checksum == ((ZoneInfoOld)other).checksum);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
TimeZone timeZone = TimeZone.getTimeZone(timeZones.get(position));
int offsetMillis = timeZone.getRawOffset();
holder.time.setText(String.format(
Locale.getDefault(),
"GMT%s%02d:%02d",
offsetMillis >= 0 ? "+" : "",
TimeUnit.MILLISECONDS.toHours(offsetMillis),
TimeUnit.MILLISECONDS.toMinutes(Math.abs(offsetMillis)) % TimeUnit.HOURS.toMinutes(1)
));
holder.title.setText(timeZone.getDisplayName(Locale.getDefault()));
holder.itemView.setOnClickListener(v -> holder.checkBox.toggle());
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked((boolean) PreferenceData.TIME_ZONE_ENABLED.getSpecificValue(holder.itemView.getContext(), timeZone.getID()));
holder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
TimeZone timeZone1 = TimeZone.getTimeZone(timeZones.get(holder.getAdapterPosition()));
PreferenceData.TIME_ZONE_ENABLED.setValue(holder.itemView.getContext(), isChecked, timeZone1.getID());
});
}
/**
* Returns true if this zone has the same raw GMT offset value and
* transition table as another zone info. If the specified
* TimeZone object is not a ZoneInfo instance, this method returns
* true if the specified TimeZone object has the same raw GMT
* offset value with no daylight saving time.
*
* @param other the ZoneInfo object to be compared with
* @return true if the given <code>TimeZone</code> has the same
* GMT offset and transition information; false, otherwise.
*/
public boolean hasSameRules(TimeZone other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (!(other instanceof ZoneInfo)) {
if (getRawOffset() != other.getRawOffset()) {
return false;
}
// if both have the same raw offset and neither observes
// DST, they have the same rule.
if ((transitions == null)
&& (useDaylightTime() == false)
&& (other.useDaylightTime() == false)) {
return true;
}
return false;
}
if (getLastRawOffset() != ((ZoneInfo)other).getLastRawOffset()) {
return false;
}
return (checksum == ((ZoneInfo)other).checksum);
}
private String toGMTFormat(String id, boolean daylight, boolean isShort, Locale l) {
TimeZone tz = ZoneInfoFile.getZoneInfo(id);
int offset = (tz.getRawOffset() + (daylight ? tz.getDSTSavings() : 0)) / 60000;
LocaleResources lr = LocaleProviderAdapter.forType(Type.CLDR).getLocaleResources(l);
ResourceBundle fd = lr.getJavaTimeFormatData();
if (offset == 0) {
return fd.getString("timezone.gmtZeroFormat");
} else {
String gmtFormat = fd.getString("timezone.gmtFormat");
String hourFormat = fd.getString("timezone.hourFormat");
if (offset > 0) {
hourFormat = hourFormat.substring(0, hourFormat.indexOf(";"));
} else {
hourFormat = hourFormat.substring(hourFormat.indexOf(";") + 1);
offset = -offset;
}
hourFormat = hourFormat
.replaceFirst("H+", (isShort ? "\\%1\\$d" : "\\%1\\$02d"))
.replaceFirst("m+", "\\%2\\$02d");
return MessageFormat.format(gmtFormat,
String.format(l, hourFormat, offset / 60, offset % 60));
}
}
/**
* Returns true if this zone has the same raw GMT offset value and
* transition table as another zone info. If the specified
* TimeZone object is not a ZoneInfoOld instance, this method returns
* true if the specified TimeZone object has the same raw GMT
* offset value with no daylight saving time.
*
* @param other the ZoneInfoOld object to be compared with
* @return true if the given <code>TimeZone</code> has the same
* GMT offset and transition information; false, otherwise.
*/
public boolean hasSameRules(TimeZone other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (!(other instanceof ZoneInfoOld)) {
if (getRawOffset() != other.getRawOffset()) {
return false;
}
// if both have the same raw offset and neither observes
// DST, they have the same rule.
if ((transitions == null)
&& (useDaylightTime() == false)
&& (other.useDaylightTime() == false)) {
return true;
}
return false;
}
if (getLastRawOffset() != ((ZoneInfoOld)other).getLastRawOffset()) {
return false;
}
return (checksum == ((ZoneInfoOld)other).checksum);
}
public void test_getAvailableIDs_I_16947622() {
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
int rawOffset = tz.getRawOffset();
assertEquals(-8 * 60 * 60 * 1000, rawOffset);
List<String> ids = Arrays.asList(TimeZone.getAvailableIDs(rawOffset));
// Obviously, for all time zones, the time zone whose raw offset we started with
// should be one of the available ids for that offset.
assertTrue(ids.toString(), ids.contains("America/Los_Angeles"));
// Any one of these might legitimately change its raw offset, though that's
// fairly unlikely, and the chances of more than one changing are very slim.
assertTrue(ids.toString(), ids.contains("America/Santa_Isabel"));
assertTrue(ids.toString(), ids.contains("America/Tijuana"));
assertTrue(ids.toString(), ids.contains("America/Vancouver"));
// j2objc: NSTimeZone does not list Canada/* as known time zone names.
// assertTrue(ids.toString(), ids.contains("Canada/Pacific"));
// assertTrue(ids.toString(), ids.contains("Canada/Yukon"));
assertTrue(ids.toString(), ids.contains("Pacific/Pitcairn"));
}
private String[] getDisplayNameArray(String id, Locale locale) {
Objects.requireNonNull(id);
Objects.requireNonNull(locale);
String[] ret =
LocaleProviderAdapter.forType(type).getLocaleResources(locale).getTimeZoneNames(id);
if (Objects.nonNull(ret) && type == LocaleProviderAdapter.Type.CLDR) {
// check for CLDR's "no inheritance marker"
for (int index = 0; index < ret.length; index++) {
TimeZone tz = null;
if (CLDR_NO_INHERITANCE_MARKER.equals(ret[index])) {
if (Objects.isNull(tz)) {
tz = TimeZone.getTimeZone(id);
}
int offset = tz.getRawOffset();
if (index == 3 || index == 4) { // daylight
offset += tz.getDSTSavings();
}
ret[index] = ZoneInfoFile.toCustomID(offset);
}
}
}
return ret;
}
@Override
public boolean equals(Object object)
{
if (!(object instanceof TimeZoneWrapper)) // matches null too
{
return false;
}
TimeZone otherTimeZone = (TimeZone) object;
/*
* This is a very simple check for equality of two time zones. It returns the wrong result if two time zones have the same UTC offset, but use different
* dates to switch to summer time.
*
* Are there such cases? How can we improve it? Maybe by testing a few more days in March and October?
*
* TODO: improve the check
*/
return (mTimeZone.getID().equals(otherTimeZone.getID()))
|| (mTimeZone.useDaylightTime() == otherTimeZone.useDaylightTime() && mTimeZone.getRawOffset() == otherTimeZone.getRawOffset()
&& mTimeZone.getDSTSavings() == otherTimeZone.getDSTSavings() && mTimeZone.inDaylightTime(TEST_DATE) == otherTimeZone.inDaylightTime(
TEST_DATE));
}
private synchronized void setTzFormatString(final TimeZone tz )
{
int zIndex = _formatString.indexOf( "ZZZ" );
if( zIndex >= 0 )
{
String ss1 = _formatString.substring( 0, zIndex );
String ss2 = _formatString.substring( zIndex+3 );
int tzOffset = tz.getRawOffset();
StringBuilder sb = new StringBuilder(_formatString.length()+10);
sb.append(ss1);
sb.append("'");
if( tzOffset >= 0 )
sb.append( '+' );
else
{
tzOffset = -tzOffset;
sb.append( '-' );
}
int raw = tzOffset / (1000*60); // Convert to seconds
int hr = raw / 60;
int min = raw % 60;
if( hr < 10 )
sb.append( '0' );
sb.append( hr );
if( min < 10 )
sb.append( '0' );
sb.append( min );
sb.append( '\'' );
sb.append(ss2);
_tzFormatString=sb.toString();
}
else
_tzFormatString=_formatString;
setMinFormatString();
}
/** 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;
if (tz.inDaylightTime(cal.getTime())) {
offset = tz.getRawOffset() + (tz.useDaylightTime()?3600000:0);
} else {
offset = tz.getRawOffset();
}
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);
}
protected static int getOffsetFromTimeZone(TimeZone tz, Date date)
{
int offset = tz.getRawOffset();
if (tz.inDaylightTime(date))
{
offset += tz.getDSTSavings();
}
return offset;
}
private String calculateGMTOffset()
{
String sign = "+";
TimeZone timeZone = TimeZone.getDefault();
int offset = timeZone.getRawOffset();
if (offset < 0)
{
sign = "-";
offset = -offset;
}
int hours = offset / (60 * 60 * 1000);
int minutes = (offset - (hours * 60 * 60 * 1000)) / (60 * 1000);
try
{
if (timeZone.useDaylightTime() && timeZone.inDaylightTime(this.getDate()))
{
hours += sign.equals("+") ? 1 : -1;
}
}
catch (ParseException e)
{
// we'll do our best and ignore daylight savings
}
return "GMT" + sign + convert(hours) + ":" + convert(minutes);
}
public cfData execute(cfSession _session, List<cfData> parameters) throws cfmRunTimeException {
cfStructData timeInfo = new cfStructData();
TimeZone tz = (TimeZone) TimeZone.getDefault().clone();
int dstCompensation = 0;
boolean dst = tz.inDaylightTime(new Date());
if (dst)
dstCompensation = tz.getDSTSavings(); // the # of milliseconds in an hour.
long offset = tz.getRawOffset() + dstCompensation;
offset = offset * -1; // cfmx livedocs for this function mandate that the
// sign be this way (which happens to be opposite of
// what Java does)
long totalOffSet = offset / 1000L;
long hour = offset / (1000L * 60L * 60L);
long minutes = offset / (1000L * 60L);
long partialHourAsMinutes = minutes % 60; // to remove all whole hours
timeInfo.setData("utctotaloffset", new cfNumberData(totalOffSet));
timeInfo.setData("utchouroffset", new cfNumberData(hour));
timeInfo.setData("utcminuteoffset", new cfNumberData(partialHourAsMinutes));
timeInfo.setData("isdston", cfBooleanData.getcfBooleanData(dst));
return timeInfo;
}
/**
* 日期类型转字符串, 带时区转换
* @param dateFormat 格式化格式, eg: yyyy-MM-dd, yyyy-MM-dd HH:mm:ss
* @return
*/
public static String convertDate2String(Date sourceDate, String dateFormat, TimeZone sourceTimeZone,
TimeZone targetTimeZone) {
if(null == sourceDate) {
return "";
}
Long targetTime = sourceDate.getTime() - sourceTimeZone.getRawOffset() + targetTimeZone.getRawOffset();
return convertDate2String(new Date(targetTime), dateFormat);
}
private String calculateGMTOffset()
{
String sign = "+";
TimeZone timeZone = TimeZone.getDefault();
int offset = timeZone.getRawOffset();
if (offset < 0)
{
sign = "-";
offset = -offset;
}
int hours = offset / (60 * 60 * 1000);
int minutes = (offset - (hours * 60 * 60 * 1000)) / (60 * 1000);
try
{
if (timeZone.useDaylightTime() && timeZone.inDaylightTime(this.getDate()))
{
hours += sign.equals("+") ? 1 : -1;
}
}
catch (ParseException e)
{
// we'll do our best and ignore daylight savings
}
return "GMT" + sign + convert(hours) + ":" + convert(minutes);
}
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;
}
public static void main(String[] args) {
System.out.println("Before JDK 8:");
TimeZone timeZoneAP = TimeZone.getTimeZone("Australia/Perth");
int offsetFromTimeZone = timeZoneAP.getRawOffset();
String userFriendlyOffsetTimeZone = formatOffset(offsetFromTimeZone);
System.out.println("Offset from TimeZone (Australia/Perth): " + userFriendlyOffsetTimeZone);
Calendar calendar = Calendar.getInstance();
// Summer time in Bucharest:
// Sunday, 31 March 2019, 1h forward - Sunday, 27 October 2019, 1 hour backward
// month 6 is a summer month in Bucharest, so you will get +03:00
// month 11 is a winter month in Bucharest, so you will get +02:00
calendar.set(2019, 11, 15);
TimeZone timeZoneEB = TimeZone.getTimeZone("Europe/Bucharest");
timeZoneEB.useDaylightTime();
int offsetFromDate = timeZoneEB.getOffset(calendar.getTime().getTime());
String userFriendlyOffsetDate = formatOffset(offsetFromDate);
System.out.println("Offset from Calendar (Europe/Bucharest): " + userFriendlyOffsetDate);
// JDK 8
System.out.println("\n\nStarting with JDK 8:");
// returns Z, which is +00:00
ZoneOffset zoneOffsetUTC = ZoneOffset.UTC;
System.out.println("ZoneOffset UTC: " + zoneOffsetUTC);
// getting the system default time zone
ZoneId defaultZoneId = ZoneOffset.systemDefault();
System.out.println("Default zone id: " + defaultZoneId);
// by default it deals with the Daylight Saving Times
LocalDateTime ldt = LocalDateTime.of(2019, 3, 15, 0, 0);
ZoneId zoneId = ZoneId.of("Europe/Bucharest");
ZoneOffset zoneOffset = zoneId.getRules().getOffset(ldt);
System.out.println("\nZoneOffset from LocalDateTime (Europe/Bucharest): " + zoneOffset);
ZoneOffset zoneOffsetFromString = ZoneOffset.of("+02:00");
System.out.println("\nZoneOffset from String: " + zoneOffsetFromString);
// for example, use it to define an OffsetDateTime or an OffsetTime
OffsetTime offsetTime = OffsetTime.now(zoneOffsetFromString);
OffsetDateTime offsetDateTime = OffsetDateTime.now(zoneOffsetFromString);
System.out.println("OffsetTime from ZoneOffset of current date: " + offsetTime);
System.out.println("OffsetDateTime from ZoneOffset of current date: " + offsetDateTime);
ZoneOffset zoneOffsetFromHoursMinutes = ZoneOffset.ofHoursMinutes(8, 30);
System.out.println("\nZoneOffset from hours and minutes: " + zoneOffsetFromHoursMinutes);
ZoneOffset zoneOffsetFromOdt = offsetDateTime.getOffset();
System.out.println("ZoneOffset from OffsetDateTime: " + zoneOffsetFromOdt);
}
/**
* Gets all available IDs that have the same value as the
* specified raw GMT offset.
*
* @param rawOffset the GMT offset in milliseconds. This
* value should not include any daylight saving time.
*
* @return an array of time zone IDs.
*/
public static String[] getAvailableIDs(int rawOffset) {
String[] result;
List<String> matched = new ArrayList<>();
List<String> IDs = ZoneInfoFile.getZoneIDs();
int[] rawOffsets = ZoneInfoFile.getRawOffsets();
loop:
for (int index = 0; index < rawOffsets.length; index++) {
if (rawOffsets[index] == rawOffset) {
byte[] indices = ZoneInfoFile.getRawOffsetIndices();
for (int i = 0; i < indices.length; i++) {
if (indices[i] == index) {
matched.add(IDs.get(i++));
while (i < indices.length && indices[i] == index) {
matched.add(IDs.get(i++));
}
break loop;
}
}
}
}
// We need to add any zones from the excluded zone list that
// currently have the same GMT offset as the specified
// rawOffset. The zones returned by this method may not be
// correct as of return to the caller if any GMT offset
// transition is happening during this GMT offset checking...
List<String> excluded = ZoneInfoFile.getExcludedZones();
if (excluded != null) {
for (String id : excluded) {
TimeZone zi = getTimeZone(id);
if (zi != null && zi.getRawOffset() == rawOffset) {
matched.add(id);
}
}
}
result = new String[matched.size()];
matched.toArray(result);
return result;
}
/**
* Convert deviation to time zone.
*
* @param deviation
* Used deviation.
* @param dst
* Is daylight saving time used.
* @return Time zone.
*/
public static TimeZone getTimeZone(final int deviation, final boolean dst) {
// Return current time zone if time zone is not used.
if (deviation == 0x8000 || deviation == -32768) {
return Calendar.getInstance().getTimeZone();
}
TimeZone tz = Calendar.getInstance().getTimeZone();
if (dst) {
// If meter is in same time zone than meter reading application.
if (tz.observesDaylightTime()
&& tz.getRawOffset() / 60000 == deviation - 60) {
return tz;
}
String[] ids = TimeZone.getAvailableIDs((deviation - 60) * 60000);
tz = null;
for (int pos = 0; pos != ids.length; ++pos) {
tz = TimeZone.getTimeZone(ids[pos]);
if (tz.observesDaylightTime()
&& tz.getRawOffset() / 60000 == deviation - 60) {
break;
}
tz = null;
}
if (tz != null) {
return tz;
}
}
if (tz != null && !tz.observesDaylightTime()
&& tz.getRawOffset() / 60000 == deviation) {
return tz;
}
String str;
DecimalFormat df = new DecimalFormat("00");
String tmp = df.format(deviation / 60) + ":"
+ df.format(Math.abs(deviation) % 60);
if (deviation == 0) {
str = "GMT";
} else if (deviation > 0) {
str = "GMT+" + tmp;
} else {
str = "GMT" + tmp;
}
return TimeZone.getTimeZone(str);
}
/**
* Writes a daylight savings time transition to a POSIX timezone
* description.
*
* @param tz Timezone
* @param buf Buffer to append to
* @param mode Transition mode
* @param day Day of transition
* @param month Month of transition
* @param dayOfWeek Day of week of transition
* @param time Time of transition in millis
* @param timeMode Mode of time transition
* @param verbose Verbose
* @param isEnd Whether this transition is leaving DST
*/
private static void appendPosixDaylightTransition(
TimeZone tz,
StringBuilder buf,
int mode,
int day,
int month,
int dayOfWeek,
int time,
int timeMode,
boolean verbose,
boolean isEnd) {
buf.append(',');
int week = day;
switch (mode) {
case 1: // SimpleTimeZone.DOM_MODE
throw Util.needToImplement(0);
case 3: // SimpleTimeZone.DOW_GE_DOM_MODE
// If the day is 1, 8, 15, 22, we can translate this to case 2.
switch (day) {
case 1:
week = 1; // 1st week of month
break;
case 8:
week = 2; // 2nd week of month
break;
case 15:
week = 3; // 3rd week of month
break;
case 22:
week = 4; // 4th week of month
break;
default:
throw new AssertionError(
"POSIX timezone format cannot represent " + tz);
}
// fall through
case 2: // SimpleTimeZone.DOW_IN_MONTH_MODE
buf.append('M');
buf.append(month + 1); // 1 <= m <= 12
buf.append('.');
if (week == -1) {
// java represents 'last week' differently from POSIX
week = 5;
}
buf.append(week); // 1 <= n <= 5, 5 means 'last'
buf.append('.');
buf.append(dayOfWeek - 1); // 0 <= d <= 6, 0=Sunday
break;
case 4: // SimpleTimeZone.DOW_LE_DOM_MODE
throw Util.needToImplement(0);
default:
throw new AssertionError("unexpected value: " + mode);
}
switch (timeMode) {
case 0: // SimpleTimeZone.WALL_TIME
break;
case 1: // SimpleTimeZone.STANDARD_TIME, e.g. Australia/Sydney
if (isEnd) {
time += tz.getDSTSavings();
}
break;
case 2: // SimpleTimeZone.UTC_TIME, e.g. Europe/Paris
time += tz.getRawOffset();
if (isEnd) {
time += tz.getDSTSavings();
}
break;
}
if (verbose || (time != 7200000)) {
// POSIX allows us to omit the time if it is 2am (the default)
buf.append('/');
appendPosixTime(buf, time);
}
}