下面列出了java.util.TimeZone#getID ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) {
TimeZone tz = TimeZone.getTimeZone("Asia/Taipei");
Locale tzLocale = new Locale("ja");
String jaStdName = "\u4e2d\u56fd\u6a19\u6e96\u6642";
String jaDstName = "\u4e2d\u56fd\u590f\u6642\u9593";
if (!tz.getDisplayName(false, TimeZone.LONG, tzLocale).equals
(jaStdName))
throw new RuntimeException("\n" + tzLocale + ": LONG, " +
"non-daylight saving name for " +
tz.getID() +
" should be " +
jaStdName);
if (!tz.getDisplayName(true, TimeZone.LONG, tzLocale).equals
(jaDstName))
throw new RuntimeException("\n" + tzLocale + ": LONG, " +
"daylight saving name for " +
tz.getID() +
" should be " +
jaDstName);
}
/**
* @param tz - timexome to be displayed
* @return - formatted timezone value
*/
@SuppressLint ("DefaultLocale")
private static String displayTimeZone(TimeZone tz) {
long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
- TimeUnit.HOURS.toMinutes(hours);
// avoid -4:-30 issue
minutes = Math.abs(minutes);
String result;
if (hours > 0) {
result = tz.getID() + " " + String.format("(GMT+%d:%02d)", hours, minutes);
} else {
result = tz.getID() + " " + String.format("(GMT%d:%02d)", hours, minutes);
}
return result;
}
public ProtocolOptions ( final int timeout1, final int timeout2, final int timeout3, final ASDUAddressType adsuAddressType, final InformationObjectAddressType informationObjectAddressType, final CauseOfTransmissionType causeOfTransmissionType, final short maxUnacknowledged, final short acknowledgeWindow, final TimeZone timeZone, final boolean ignoreDaylightSavingTime )
{
super ();
this.timeout1 = timeout1;
this.timeout2 = timeout2;
this.timeout3 = timeout3;
this.adsuAddressType = adsuAddressType;
this.informationObjectAddressType = informationObjectAddressType;
this.causeOfTransmissionType = causeOfTransmissionType;
this.maxUnacknowledged = maxUnacknowledged;
this.acknowledgeWindow = acknowledgeWindow;
this.timeZone = timeZone;
this.timeZoneId = timeZone != null ? timeZone.getID () : null;
this.ignoreDaylightSavingTime = ignoreDaylightSavingTime;
}
public TimeWithTimeZoneString withTimeZone(TimeZone timeZone) {
if (this.timeZone.equals(timeZone)) {
return this;
}
String localTimeString = localTime.toString();
String v;
String fraction;
int i = localTimeString.indexOf('.');
if (i >= 0) {
v = localTimeString.substring(0, i);
fraction = localTimeString.substring(i + 1);
} else {
v = localTimeString;
fraction = null;
}
final DateTimeUtils.PrecisionTime pt =
DateTimeUtils.parsePrecisionDateTimeLiteral(v,
new SimpleDateFormat(DateTimeUtils.TIME_FORMAT_STRING, Locale.ROOT),
this.timeZone, -1);
pt.getCalendar().setTimeZone(timeZone);
if (fraction != null) {
return new TimeWithTimeZoneString(
pt.getCalendar().get(Calendar.HOUR_OF_DAY),
pt.getCalendar().get(Calendar.MINUTE),
pt.getCalendar().get(Calendar.SECOND),
timeZone.getID())
.withFraction(fraction);
}
return new TimeWithTimeZoneString(
pt.getCalendar().get(Calendar.HOUR_OF_DAY),
pt.getCalendar().get(Calendar.MINUTE),
pt.getCalendar().get(Calendar.SECOND),
timeZone.getID());
}
/**
* After reading an object from the input stream, the format
* pattern in the object is verified.
* <p>
* @exception InvalidObjectException if the pattern is invalid
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
compiledPattern = compile(pattern);
} catch (Exception e) {
throw new InvalidObjectException("invalid pattern");
}
if (serialVersionOnStream < 1) {
// didn't have defaultCenturyStart field
initializeDefaultCentury();
}
else {
// fill in dependent transient field
parseAmbiguousDatesAsAfter(defaultCenturyStart);
}
serialVersionOnStream = currentSerialVersion;
// If the deserialized object has a SimpleTimeZone, try
// to replace it with a ZoneInfo equivalent in order to
// be compatible with the SimpleTimeZone-based
// implementation as much as possible.
TimeZone tz = getTimeZone();
if (tz instanceof SimpleTimeZone) {
String id = tz.getID();
TimeZone zi = TimeZone.getTimeZone(id);
if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
setTimeZone(zi);
}
}
}
public static TimeZone getTimeZone(String timeZone) {
timeZone = timeZone.trim();
TimeZone zone = TimeZone.getTimeZone(timeZone);
String id = zone.getID();
if (id.compareTo(timeZone) != 0) {
throw new IllegalArgumentException("Bad timezone name: '" + timeZone + "'");
}
return zone;
}
/**
* Gets a time zone instance for a JDK TimeZone.
* <p>
* DateTimeZone only accepts a subset of the IDs from TimeZone. The
* excluded IDs are the short three letter form (except UTC). This
* method will attempt to convert between time zones created using the
* short IDs and the full version.
* <p>
* This method is not designed to parse time zones with rules created by
* applications using <code>SimpleTimeZone</code> directly.
*
* @param zone the zone to convert, null means default
* @return the DateTimeZone object for the zone
* @throws IllegalArgumentException if the zone is not recognised
*/
public static DateTimeZone forTimeZone(TimeZone zone) {
if (zone == null) {
return getDefault();
}
final String id = zone.getID();
if (id.equals("UTC")) {
return DateTimeZone.UTC;
}
// Convert from old alias before consulting provider since they may differ.
DateTimeZone dtz = null;
String convId = getConvertedId(id);
if (convId != null) {
dtz = cProvider.getZone(convId);
}
if (dtz == null) {
dtz = cProvider.getZone(id);
}
if (dtz != null) {
return dtz;
}
// Support GMT+/-hh:mm formats
if (convId == null) {
convId = zone.getID();
if (convId.startsWith("GMT+") || convId.startsWith("GMT-")) {
convId = convId.substring(3);
int offset = parseOffset(convId);
if (offset == 0L) {
return DateTimeZone.UTC;
} else {
convId = printOffset(offset);
return fixedOffsetZone(convId, offset);
}
}
}
throw new IllegalArgumentException("The datetime zone id '" + id + "' is not recognised");
}
/**
* Gets a time zone instance for a JDK TimeZone.
* <p>
* DateTimeZone only accepts a subset of the IDs from TimeZone. The
* excluded IDs are the short three letter form (except UTC). This
* method will attempt to convert between time zones created using the
* short IDs and the full version.
* <p>
* This method is not designed to parse time zones with rules created by
* applications using <code>SimpleTimeZone</code> directly.
*
* @param zone the zone to convert, null means default
* @return the DateTimeZone object for the zone
* @throws IllegalArgumentException if the zone is not recognised
*/
public static DateTimeZone forTimeZone(TimeZone zone) {
if (zone == null) {
return getDefault();
}
final String id = zone.getID();
if (id.equals("UTC")) {
return DateTimeZone.UTC;
}
// Convert from old alias before consulting provider since they may differ.
DateTimeZone dtz = null;
String convId = getConvertedId(id);
if (convId != null) {
dtz = cProvider.getZone(convId);
}
if (dtz == null) {
dtz = cProvider.getZone(id);
}
if (dtz != null) {
return dtz;
}
// Support GMT+/-hh:mm formats
if (convId == null) {
convId = zone.getDisplayName();
if (convId.startsWith("GMT+") || convId.startsWith("GMT-")) {
convId = convId.substring(3);
int offset = parseOffset(convId);
if (offset == 0L) {
return DateTimeZone.UTC;
} else {
convId = printOffset(offset);
return fixedOffsetZone(convId, offset);
}
}
}
throw new IllegalArgumentException("The datetime zone id '" + id + "' is not recognised");
}
/**
* After reading an object from the input stream, the format
* pattern in the object is verified.
* <p>
* @exception InvalidObjectException if the pattern is invalid
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
compiledPattern = compile(pattern);
} catch (Exception e) {
throw new InvalidObjectException("invalid pattern");
}
if (serialVersionOnStream < 1) {
// didn't have defaultCenturyStart field
initializeDefaultCentury();
}
else {
// fill in dependent transient field
parseAmbiguousDatesAsAfter(defaultCenturyStart);
}
serialVersionOnStream = currentSerialVersion;
// If the deserialized object has a SimpleTimeZone, try
// to replace it with a ZoneInfo equivalent in order to
// be compatible with the SimpleTimeZone-based
// implementation as much as possible.
TimeZone tz = getTimeZone();
if (tz instanceof SimpleTimeZone) {
String id = tz.getID();
TimeZone zi = TimeZone.getTimeZone(id);
if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
setTimeZone(zi);
}
}
}
/**
* After reading an object from the input stream, the format
* pattern in the object is verified.
* <p>
* @exception InvalidObjectException if the pattern is invalid
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
compiledPattern = compile(pattern);
} catch (Exception e) {
throw new InvalidObjectException("invalid pattern");
}
if (serialVersionOnStream < 1) {
// didn't have defaultCenturyStart field
initializeDefaultCentury();
}
else {
// fill in dependent transient field
parseAmbiguousDatesAsAfter(defaultCenturyStart);
}
serialVersionOnStream = currentSerialVersion;
// If the deserialized object has a SimpleTimeZone, try
// to replace it with a ZoneInfo equivalent in order to
// be compatible with the SimpleTimeZone-based
// implementation as much as possible.
TimeZone tz = getTimeZone();
if (tz instanceof SimpleTimeZone) {
String id = tz.getID();
TimeZone zi = TimeZone.getTimeZone(id);
if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
setTimeZone(zi);
}
}
}
/**
* After reading an object from the input stream, the format
* pattern in the object is verified.
* <p>
* @exception InvalidObjectException if the pattern is invalid
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
compiledPattern = compile(pattern);
} catch (Exception e) {
throw new InvalidObjectException("invalid pattern");
}
if (serialVersionOnStream < 1) {
// didn't have defaultCenturyStart field
initializeDefaultCentury();
}
else {
// fill in dependent transient field
parseAmbiguousDatesAsAfter(defaultCenturyStart);
}
serialVersionOnStream = currentSerialVersion;
// If the deserialized object has a SimpleTimeZone, try
// to replace it with a ZoneInfo equivalent in order to
// be compatible with the SimpleTimeZone-based
// implementation as much as possible.
TimeZone tz = getTimeZone();
if (tz instanceof SimpleTimeZone) {
String id = tz.getID();
TimeZone zi = TimeZone.getTimeZone(id);
if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
setTimeZone(zi);
}
}
}
private static void test(int offsetMinutes)
throws DatatypeConfigurationException {
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().
newXMLGregorianCalendar();
calendar.setTimezone(60 + offsetMinutes);
TimeZone timeZone = calendar.getTimeZone(DatatypeConstants.FIELD_UNDEFINED);
String expected = (offsetMinutes < 10 ? "GMT+01:0" : "GMT+01:")
+ offsetMinutes;
if (!timeZone.getID().equals(expected)) {
throw new RuntimeException("Test failed: expected timezone: " +
expected + " Actual: " + timeZone.getID());
}
}
private static void test(int offsetMinutes)
throws DatatypeConfigurationException {
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().
newXMLGregorianCalendar();
calendar.setTimezone(60 + offsetMinutes);
TimeZone timeZone = calendar.getTimeZone(DatatypeConstants.FIELD_UNDEFINED);
String expected = (offsetMinutes < 10 ? "GMT+01:0" : "GMT+01:")
+ offsetMinutes;
if (!timeZone.getID().equals(expected)) {
throw new RuntimeException("Test failed: expected timezone: " +
expected + " Actual: " + timeZone.getID());
}
}
/**
* Gets a time zone instance for a JDK TimeZone.
* <p>
* DateTimeZone only accepts a subset of the IDs from TimeZone. The
* excluded IDs are the short three letter form (except UTC). This
* method will attempt to convert between time zones created using the
* short IDs and the full version.
* <p>
* This method is not designed to parse time zones with rules created by
* applications using <code>SimpleTimeZone</code> directly.
*
* @param zone the zone to convert, null means default
* @return the DateTimeZone object for the zone
* @throws IllegalArgumentException if the zone is not recognised
*/
public static DateTimeZone forTimeZone(TimeZone zone) {
if (zone == null) {
return getDefault();
}
final String id = zone.getID();
if (id.equals("UTC")) {
return DateTimeZone.UTC;
}
// Convert from old alias before consulting provider since they may differ.
DateTimeZone dtz = null;
String convId = getConvertedId(id);
if (convId != null) {
dtz = cProvider.getZone(convId);
}
if (dtz == null) {
dtz = cProvider.getZone(id);
}
if (dtz != null) {
return dtz;
}
// Support GMT+/-hh:mm formats
if (convId == null) {
convId = zone.getID();
if (convId.startsWith("GMT+") || convId.startsWith("GMT-")) {
convId = convId.substring(3);
int offset = parseOffset(convId);
if (offset == 0L) {
return DateTimeZone.UTC;
} else {
convId = printOffset(offset);
return fixedOffsetZone(convId, offset);
}
}
}
throw new IllegalArgumentException("The datetime zone id '" + id + "' is not recognised");
}
/**
* Gets a time zone instance for a JDK TimeZone.
* <p>
* DateTimeZone only accepts a subset of the IDs from TimeZone. The
* excluded IDs are the short three letter form (except UTC). This
* method will attempt to convert between time zones created using the
* short IDs and the full version.
* <p>
* This method is not designed to parse time zones with rules created by
* applications using <code>SimpleTimeZone</code> directly.
*
* @param zone the zone to convert, null means default
* @return the DateTimeZone object for the zone
* @throws IllegalArgumentException if the zone is not recognised
*/
public static DateTimeZone forTimeZone(TimeZone zone) {
if (zone == null) {
return getDefault();
}
final String id = zone.getID();
if (id.equals("UTC")) {
return DateTimeZone.UTC;
}
// Convert from old alias before consulting provider since they may differ.
DateTimeZone dtz = null;
String convId = getConvertedId(id);
if (convId != null) {
dtz = cProvider.getZone(convId);
}
if (dtz == null) {
dtz = cProvider.getZone(id);
}
if (dtz != null) {
return dtz;
}
// Support GMT+/-hh:mm formats
if (convId == null) {
convId = zone.getDisplayName();
if (convId.startsWith("GMT+") || convId.startsWith("GMT-")) {
convId = convId.substring(3);
int offset = parseOffset(convId);
if (offset == 0L) {
return DateTimeZone.UTC;
} else {
convId = printOffset(offset);
return fixedOffsetZone(convId, offset);
}
}
}
throw new IllegalArgumentException("The datetime zone id '" + id + "' is not recognised");
}
/**
* {@inheritDoc}
*/
@Override
public String marshal(TimeZone object) {
return object.getID();
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return (tz.getID());
}
public static String getTimeZoneId(TimeZone tz) {
return tz.getID();
}
@Override
public CharSequence toCharSequence(TimeZone value, Schema schema, LogicalType type) {
return value.getID();
}
@Test
public void setGlobalTimezone() throws Throwable {
ICalendar ical = new ICalendar();
ical.getProperties().clear();
VEvent event = new VEvent();
event.getProperties().clear();
event.setDateStart(utc("1996-07-04 12:00:00"));
ical.addEvent(event);
TimeZone nyTimezone = TimeZone.getTimeZone("America/New_York");
VTimezone nyComponent = new VTimezone(nyTimezone.getID());
ical.getTimezoneInfo().setDefaultTimezone(new TimezoneAssignment(nyTimezone, nyComponent));
TimeZone laTimezone = TimeZone.getTimeZone("America/Los_Angeles");
VTimezone laComponent = new VTimezone(laTimezone.getID());
StringWriter sw = new StringWriter();
ICalWriter writer = new ICalWriter(sw, V2_0);
writer.write(ical);
writer.setGlobalTimezone(new TimezoneAssignment(laTimezone, laComponent));
writer.write(ical);
writer.close();
//@formatter:off
String expected =
"BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"BEGIN:VTIMEZONE\r\n" +
"TZID:America/New_York\r\n" +
"END:VTIMEZONE\r\n" +
"BEGIN:VEVENT\r\n" +
"DTSTART;TZID=America/New_York:19960704T080000\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n" +
"BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"BEGIN:VTIMEZONE\r\n" +
"TZID:America/Los_Angeles\r\n" +
"END:VTIMEZONE\r\n" +
"BEGIN:VEVENT\r\n" +
"DTSTART;TZID=America/Los_Angeles:19960704T050000\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n";
//@formatter:on
String actual = sw.toString();
assertEquals(expected, actual);
}