下面列出了java.time.zone.ZoneRulesException#java.util.SimpleTimeZone 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a time object from a given date - if the date is between 1950
* and 2049 a UTCTime object is generated, otherwise a GeneralizedTime
* is used.
*
* @param time a date object representing the time of interest.
*/
public Time(
Date time)
{
SimpleTimeZone tz = new SimpleTimeZone(0, "Z");
SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss");
dateF.setTimeZone(tz);
String d = dateF.format(time) + "Z";
int year = Integer.parseInt(d.substring(0, 4));
if (year < 1950 || year > 2049)
{
this.time = new DERGeneralizedTime(d);
}
else
{
this.time = new DERUTCTime(d.substring(2));
}
}
public void testForStyle_shortTime() throws Exception {
DateTimeFormatter f = DateTimeFormat.shortTime();
DateTimeFormatter g = DateTimeFormat.forStyle("-S");
assertSame(g, f);
DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
String expect = DateFormat.getTimeInstance(DateFormat.SHORT, UK).format(dt.toDate());
assertEquals(expect, f.print(dt));
expect = DateFormat.getTimeInstance(DateFormat.SHORT, US).format(dt.toDate());
assertEquals(expect, f.withLocale(US).print(dt));
expect = DateFormat.getTimeInstance(DateFormat.SHORT, FRANCE).format(dt.toDate());
assertEquals(expect, f.withLocale(FRANCE).print(dt));
if (TimeZone.getDefault() instanceof SimpleTimeZone) {
// skip test, as it needs historical time zone info
} else {
DateTime date = new DateTime(
DateFormat.getTimeInstance(DateFormat.SHORT, FRANCE).parse(expect));
assertEquals(date, f.withLocale(FRANCE).parseDateTime(expect));
}
}
/**
* Creates a time object from a given date and locale - if the date is between 1950
* and 2049 a UTCTime object is generated, otherwise a GeneralizedTime
* is used. You may need to use this constructor if the default locale
* doesn't use a Gregorian calender so that the GeneralizedTime produced is compatible with other ASN.1 implementations.
*
* @param time a date object representing the time of interest.
* @param locale an appropriate Locale for producing an ASN.1 GeneralizedTime value.
*/
public Time(
Date time,
Locale locale)
{
SimpleTimeZone tz = new SimpleTimeZone(0, "Z");
SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss", locale);
dateF.setTimeZone(tz);
String d = dateF.format(time) + "Z";
int year = Integer.parseInt(d.substring(0, 4));
if (year < 1950 || year > 2049)
{
this.time = new DERGeneralizedTime(d);
}
else
{
this.time = new DERUTCTime(d.substring(2));
}
}
/**
* Returns the milliseconds for midnight of the first Monday after
* 1-Jan-1900, ignoring daylight savings.
*
* @return The milliseconds.
*
* @since 1.0.7
*/
public static long firstMondayAfter1900() {
int offset = TimeZone.getDefault().getRawOffset();
TimeZone z = new SimpleTimeZone(offset, "UTC-" + offset);
// calculate midnight of first monday after 1/1/1900 relative to
// current locale
Calendar cal = new GregorianCalendar(z);
cal.set(1900, 0, 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
cal.add(Calendar.DATE, 1);
}
//return cal.getTimeInMillis();
// preceding code won't work with JDK 1.3
return cal.getTime().getTime();
}
/**
* Get the age of the film list.
*
* @return Age as a {@link java.util.Date} object.
*/
public Date getAgeAsDate() {
String date;
if (!metaDaten[ListeFilme.FILMLISTE_DATUM_GMT_NR].isEmpty()) {
date = metaDaten[ListeFilme.FILMLISTE_DATUM_GMT_NR];
sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
} else {
date = metaDaten[ListeFilme.FILMLISTE_DATUM_NR];
}
Date filmDate = null;
try {
filmDate = sdf.parse(date);
} catch (ParseException ignored) {
}
return filmDate;
}
@Test
public void testEquals() {
StorableTimeFence fence1 = StorableTimeFence.inInterval(2, 300);
StorableTimeFence fence2 = StorableTimeFence.inInterval(2, 400);
StorableTimeFence fence3 = StorableTimeFence.inIntervalOfDay(DAY_OF_WEEK_MONDAY, mTimeZone, 20, 300);
StorableTimeFence fence4 = StorableTimeFence.inIntervalOfDay(DAY_OF_WEEK_MONDAY, mTimeZone, 20, 300);
StorableTimeFence fence5 = StorableTimeFence.inIntervalOfDay(DAY_OF_WEEK_MONDAY, new SimpleTimeZone(3, "1"), 20, 400);
StorableTimeFence fence6 = StorableTimeFence.aroundTimeInstant(TimeFence.TIME_INSTANT_SUNRISE, 0, 1);
StorableTimeFence fence7 = StorableTimeFence.aroundTimeInstant(TimeFence.TIME_INSTANT_SUNRISE, 0, 1);
StorableTimeFence fence8 = StorableTimeFence.inTimeInterval(TIME_INTERVAL_AFTERNOON);
StorableTimeFence fence9 = StorableTimeFence.inTimeInterval(TimeFence.TIME_INTERVAL_WEEKDAY);
assertThat(fence1.equals(fence1), is(true));
assertThat(fence3.equals(fence4), is(true));
assertThat(fence2.equals(null), is(false));
assertThat(fence4.equals(fence5), is(false));
assertThat(fence5.equals(fence6), is(false));
assertThat(fence6.equals(fence7), is(true));
assertThat(fence8.equals(fence9), is(false));
}
/**
* Queries if the specified date is in Daylight Saving Time.
*/
public boolean inDaylightTime(Date date) {
if (date == null) {
throw new NullPointerException();
}
if (transitions == null) {
return false;
}
long utc = date.getTime() - rawOffsetDiff;
int index = getTransitionIndex(utc, UTC_TIME);
// before transitions in the transition table
if (index < 0) {
return false;
}
// the time is in the table range.
if (index < transitions.length) {
return (transitions[index] & DST_MASK) != 0;
}
// beyond the transition table
SimpleTimeZone tz = getLastRule();
if (tz != null) {
return tz.inDaylightTime(date);
}
return false;
}
public DatenFilmlisteUrl(String url, String art) {
sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
makeArr();
arr[FILM_UPDATE_SERVER_URL_NR] = url;
arr[FILM_UPDATE_SERVER_PRIO_NR] = DatenFilmlisteUrl.FILM_UPDATE_SERVER_PRIO_1;
arr[FILM_UPDATE_SERVER_DATUM_NR] = "";
arr[FILM_UPDATE_SERVER_ZEIT_NR] = "";
arr[FILM_UPDATE_SERVER_ART_NR] = art;
}
private SimpleDateFormat parseDateFormat(Object whenPattern, Object timezone) throws IOException {
if (whenPattern == null) {
throw new IOException("field 'whenPattern' not found");
}
format = new SimpleDateFormat((String) whenPattern);
if (timezone != null) {
if (timezone instanceof Number) {
Number tz = (Number) timezone;
format.setTimeZone(new SimpleTimeZone((int) (tz.doubleValue() * 3600000), tz.toString()));
}
else if (timezone instanceof String) {
format.setTimeZone(SimpleTimeZone.getTimeZone((String) timezone));
if (format.getTimeZone().equals(SimpleTimeZone.getTimeZone("GMT"))) {
LOGGER.warn(
"'timezone' value defined as '{}' but Java interpreted this as GMT; are you sure this is a valid value?",
timezone);
}
}
else {
LOGGER.warn("timezone '{}' is not a valid format; it must be a number or a String", timezone);
// return format without a set timezone
}
data.setMetadata("timezone", format.getTimeZone().getDisplayName());
}
else {
LOGGER.info("no 'timezone' value defined; defaulting to {}, ({})", format.getTimeZone().getID(),
format.getTimeZone().getRawOffset() / 3600000.0);
}
return format;
}
/**
* Returns a SimpleTimeZone object representing the last GMT
* offset and DST schedule or null if this time zone doesn't
* observe DST.
*/
private synchronized SimpleTimeZone getLastRule() {
if (lastRule == null) {
lastRule = getLastRuleInstance();
}
return lastRule;
}
@Test
public void parseRfc822Date() throws ParseException {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
String formatted = sdf.format(date);
Date expected = sdf.parse(formatted);
Date actual = DateUtils.parseRFC822Date(formatted);
assertEquals(expected, actual);
}
@Test(expectedExceptions = ZoneRulesException.class)
public void test_systemDefault_unableToConvert_unknownId() {
TimeZone current = TimeZone.getDefault();
try {
TimeZone.setDefault(new SimpleTimeZone(127, "SomethingWeird"));
ZoneId.systemDefault();
} finally {
TimeZone.setDefault(current);
}
}
/**
* java.util.SimpleTimeZone#setRawOffset(int)
*/
public void test_setRawOffsetI() {
// Test for method void java.util.SimpleTimeZone.setRawOffset(int)
st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
int off = st1.getRawOffset();
st1.setRawOffset(1000);
boolean val = st1.getRawOffset() == 1000;
st1.setRawOffset(off);
assertTrue("Incorrect offset set", val);
}
public void testDst_1stSundayApril_1stSundayOctober_DefaultTime() {
TimeZone timeZone = new SimpleTimeZone(-18000000, "EST",
Calendar.APRIL, 1, -Calendar.SUNDAY, 7200000,
Calendar.OCTOBER, -1, Calendar.SUNDAY, 7200000,
3600000);
checkDstTransitionTimes(timeZone, 1998,
"1998-04-05T07:00:00.000+0000",
"1998-10-25T06:00:00.000+0000");
checkDstTransitionTimes(timeZone, 2014,
"2014-04-06T07:00:00.000+0000",
"2014-10-26T06:00:00.000+0000");
}
/**
* Queries if the specified date is in Daylight Saving Time.
*/
public boolean inDaylightTime(Date date) {
if (date == null) {
throw new NullPointerException();
}
if (transitions == null) {
return false;
}
long utc = date.getTime() - rawOffsetDiff;
int index = getTransitionIndex(utc, UTC_TIME);
// before transitions in the transition table
if (index < 0) {
return false;
}
// the time is in the table range.
if (index < transitions.length) {
return (transitions[index] & DST_MASK) != 0;
}
// beyond the transition table
SimpleTimeZone tz = getLastRule();
if (tz != null) {
return tz.inDaylightTime(date);
}
return false;
}
/**
* java.util.SimpleTimeZone#clone()
*/
public void test_clone() {
// Test for method java.lang.Object java.util.SimpleTimeZone.clone()
SimpleTimeZone st1 = new SimpleTimeZone(1000, "TEST",
Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
-1, Calendar.SUNDAY, 0);
SimpleTimeZone stA = new SimpleTimeZone(1, "Gah");
assertTrue("Clone resulted in same reference", st1.clone() != st1);
assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) st1
.clone()).equals(st1));
assertTrue("Clone resulted in same reference", stA.clone() != stA);
assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) stA
.clone()).equals(stA));
}
/**
* Returns a SimpleTimeZone object that represents the last
* known daylight saving time rules.
*
* @return a SimpleTimeZone object or null if this time zone
* doesn't observe DST.
*/
public SimpleTimeZone getLastRuleInstance() {
if (simpleTimeZoneParams == null) {
return null;
}
if (simpleTimeZoneParams.length == 10) {
return new SimpleTimeZone(getLastRawOffset(), getID(),
simpleTimeZoneParams[0],
simpleTimeZoneParams[1],
simpleTimeZoneParams[2],
simpleTimeZoneParams[3],
simpleTimeZoneParams[4],
simpleTimeZoneParams[5],
simpleTimeZoneParams[6],
simpleTimeZoneParams[7],
simpleTimeZoneParams[8],
simpleTimeZoneParams[9],
dstSavings);
}
return new SimpleTimeZone(getLastRawOffset(), getID(),
simpleTimeZoneParams[0],
simpleTimeZoneParams[1],
simpleTimeZoneParams[2],
simpleTimeZoneParams[3],
simpleTimeZoneParams[4],
simpleTimeZoneParams[5],
simpleTimeZoneParams[6],
simpleTimeZoneParams[7],
dstSavings);
}
public void testToDate_springDST() {
LocalDateTime base = new LocalDateTime(2007, 4, 2, 0, 20, 0, 0);
SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight",
Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000);
TimeZone currentZone = TimeZone.getDefault();
try {
TimeZone.setDefault(testZone);
Date test = base.toDate();
check(base, 2007, 4, 2, 0, 20, 0, 0);
assertEquals("Mon Apr 02 01:00:00 GMT+02:00 2007", test.toString());
} finally {
TimeZone.setDefault(currentZone);
}
}
/**
* 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);
}
}
}
/**
* Returns a SimpleTimeZone object that represents the last
* known daylight saving time rules.
*
* @return a SimpleTimeZone object or null if this time zone
* doesn't observe DST.
*/
public SimpleTimeZone getLastRuleInstance() {
if (simpleTimeZoneParams == null) {
return null;
}
if (simpleTimeZoneParams.length == 10) {
return new SimpleTimeZone(getLastRawOffset(), getID(),
simpleTimeZoneParams[0],
simpleTimeZoneParams[1],
simpleTimeZoneParams[2],
simpleTimeZoneParams[3],
simpleTimeZoneParams[4],
simpleTimeZoneParams[5],
simpleTimeZoneParams[6],
simpleTimeZoneParams[7],
simpleTimeZoneParams[8],
simpleTimeZoneParams[9],
dstSavings);
}
return new SimpleTimeZone(getLastRawOffset(), getID(),
simpleTimeZoneParams[0],
simpleTimeZoneParams[1],
simpleTimeZoneParams[2],
simpleTimeZoneParams[3],
simpleTimeZoneParams[4],
simpleTimeZoneParams[5],
simpleTimeZoneParams[6],
simpleTimeZoneParams[7],
dstSavings);
}
@Test(expectedExceptions = ZoneRulesException.class)
public void test_systemDefault_unableToConvert_unknownId() {
TimeZone current = TimeZone.getDefault();
try {
TimeZone.setDefault(new SimpleTimeZone(127, "SomethingWeird"));
ZoneId.systemDefault();
} finally {
TimeZone.setDefault(current);
}
}
/**
* Returns a SimpleTimeZone object that represents the last
* known daylight saving time rules.
*
* @return a SimpleTimeZone object or null if this time zone
* doesn't observe DST.
*/
public SimpleTimeZone getLastRuleInstance() {
if (simpleTimeZoneParams == null) {
return null;
}
if (simpleTimeZoneParams.length == 10) {
return new SimpleTimeZone(getLastRawOffset(), getID(),
simpleTimeZoneParams[0],
simpleTimeZoneParams[1],
simpleTimeZoneParams[2],
simpleTimeZoneParams[3],
simpleTimeZoneParams[4],
simpleTimeZoneParams[5],
simpleTimeZoneParams[6],
simpleTimeZoneParams[7],
simpleTimeZoneParams[8],
simpleTimeZoneParams[9],
dstSavings);
}
return new SimpleTimeZone(getLastRawOffset(), getID(),
simpleTimeZoneParams[0],
simpleTimeZoneParams[1],
simpleTimeZoneParams[2],
simpleTimeZoneParams[3],
simpleTimeZoneParams[4],
simpleTimeZoneParams[5],
simpleTimeZoneParams[6],
simpleTimeZoneParams[7],
dstSavings);
}
/**
* Queries if the specified date is in Daylight Saving Time.
*/
public boolean inDaylightTime(Date date) {
if (date == null) {
throw new NullPointerException();
}
if (transitions == null) {
return false;
}
long utc = date.getTime() - rawOffsetDiff;
int index = getTransitionIndex(utc, UTC_TIME);
// before transitions in the transition table
if (index < 0) {
return false;
}
// the time is in the table range.
if (index < transitions.length) {
return (transitions[index] & DST_MASK) != 0;
}
// beyond the transition table
SimpleTimeZone tz = getLastRule();
if (tz != null) {
return tz.inDaylightTime(date);
}
return false;
}
public void Test4278609() {
SimpleTimeZone tz = new SimpleTimeZone(0, "MyTimeZone",
/* DST start day: August, 1, 0:00 */
Calendar.AUGUST, 1, 0, 0,
/* DST end day: January, 1, 0:00 (wall-clock)*/
Calendar.JANUARY, 1, 0, 0,
60 * 60 * 1000);
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
// setting a date using GMT zone just after the end rule of tz zone
cal.clear();
cal.set(Calendar.ERA, GregorianCalendar.AD);
cal.set(1998, Calendar.DECEMBER, 31, 23, 01, 00);
Date date = cal.getTime();
int millis = cal.get(Calendar.HOUR_OF_DAY) * 3600000
+ cal.get(Calendar.MINUTE) * 60000
+ cal.get(Calendar.SECOND) * 1000
+ cal.get(Calendar.MILLISECOND);
/* we must use standard local time */
millis += tz.getRawOffset();
int offset = tz.getOffset(cal.get(Calendar.ERA),
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DATE),
cal.get(Calendar.DAY_OF_WEEK),
millis);
if (offset != 0) {
SimpleDateFormat format = new SimpleDateFormat("dd MMM HH:mm:ss zzz",
Locale.US);
format.setTimeZone(tz);
errln("Wrong DST transition: " + tz
+ "\na date just after DST = " + format.format(date)
+ "\ngetOffset = " + offset);
}
}
private void verifyFormatTimezone(String timeZoneId, String expected1, String expected2,
Date date) {
SimpleDateFormat format = new SimpleDateFormat("", Locale.ENGLISH);
format.setTimeZone(SimpleTimeZone.getTimeZone(timeZoneId));
format.applyPattern("z, zzzz");
assertEquals("Test z for TimeZone : " + timeZoneId, expected1, format.format(date));
format.applyPattern("Z, ZZZZ");
assertEquals("Test Z for TimeZone : " + timeZoneId, expected2, format.format(date));
}
@Test(expectedExceptions = ZoneRulesException.class)
public void test_systemDefault_unableToConvert_unknownId() {
TimeZone current = TimeZone.getDefault();
try {
TimeZone.setDefault(new SimpleTimeZone(127, "SomethingWeird"));
ZoneId.systemDefault();
} finally {
TimeZone.setDefault(current);
}
}
/**
* Queries if the specified date is in Daylight Saving Time.
*/
public boolean inDaylightTime(Date date) {
if (date == null) {
throw new NullPointerException();
}
if (transitions == null) {
return false;
}
long utc = date.getTime() - rawOffsetDiff;
int index = getTransitionIndex(utc, UTC_TIME);
// before transitions in the transition table
if (index < 0) {
return false;
}
// the time is in the table range.
if (index < transitions.length) {
return (transitions[index] & DST_MASK) != 0;
}
// beyond the transition table
SimpleTimeZone tz = getLastRule();
if (tz != null) {
return tz.inDaylightTime(date);
}
return false;
}
/**
* 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);
}
}
}
/**
* Takes time in milliseconds and returns the formatted date and time according to Elasticsearch
*
* @param time long time in millis
* @return timeStamp formatted according to the Elasticsearch
*/
private static String getFormattedDate(long time) {
Date date = new Date(time);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(date);
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SSS");
timeFormat.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
String formattedTime = timeFormat.format(date);
return formattedDate + "T" + formattedTime + "Z";
}