下面列出了java.util.TimeZone#getDefault ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Takes a JarInputStream and converts into a pack-stream.
* <p>
* Closes its input but not its output. (Pack200 archives are appendable.)
* <p>
* The modification time and deflation hint attributes are not available,
* for the jar-manifest file and the directory containing the file.
*
* @see #MODIFICATION_TIME
* @see #DEFLATION_HINT
* @param in a JarInputStream
* @param out an OutputStream
* @exception IOException if an error is encountered.
*/
public synchronized void pack(JarInputStream in, OutputStream out) throws IOException {
assert(Utils.currentInstance.get() == null);
TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null :
TimeZone.getDefault();
try {
Utils.currentInstance.set(this);
if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
if ("0".equals(props.getProperty(Pack200.Packer.EFFORT))) {
Utils.copyJarFile(in, out);
} else {
(new DoPack()).run(in, out);
}
} finally {
Utils.currentInstance.set(null);
if (tz != null) TimeZone.setDefault(tz);
in.close();
}
}
protected TimestampTreeReader(TimeZone timeZone, int columnId, InStream presentStream, InStream dataStream,
InStream nanosStream, OrcProto.ColumnEncoding encoding, boolean skipCorrupt)
throws IOException {
super(columnId, presentStream);
this.skipCorrupt = skipCorrupt;
this.baseTimestampMap = new HashMap<>();
this.readerTimeZone = timeZone;
this.writerTimeZone = TimeZone.getDefault();
this.hasSameTZRules = writerTimeZone.hasSameRules(readerTimeZone);
this.base_timestamp = getBaseTimestamp(readerTimeZone.getID());
if (encoding != null) {
checkEncoding(encoding);
if (dataStream != null) {
this.data = createIntegerReader(encoding.getKind(), dataStream, true, skipCorrupt);
}
if (nanosStream != null) {
this.nanos = createIntegerReader(encoding.getKind(), nanosStream, false, skipCorrupt);
}
}
}
/**
* Some checks for the getStart() method.
*/
@Test
public void testGetStart() {
Locale saved = Locale.getDefault();
Locale.setDefault(Locale.ITALY);
TimeZone savedZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Rome"));
Calendar cal = Calendar.getInstance(Locale.ITALY);
cal.set(2006, Calendar.JANUARY, 16, 3, 47, 0);
cal.set(Calendar.MILLISECOND, 0);
Minute m = new Minute(47, 3, 16, 1, 2006);
assertEquals(cal.getTime(), m.getStart());
Locale.setDefault(saved);
TimeZone.setDefault(savedZone);
}
/**
* Test 6 checks that 9am on Sunday 28 March 2004 converts to the timeline
* value and back again correctly. Note that Saturday and Sunday are
* excluded from the timeline, so we expect the value to map to 9am on
* Monday 29 March 2004. This is during daylight saving.
*/
public void test6() {
TimeZone savedZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Calendar cal = Calendar.getInstance(Locale.UK);
cal.set(Calendar.YEAR, 2004);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DAY_OF_MONTH, 28);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
SegmentedTimeline timeline = getTimeline();
long value = timeline.toTimelineValue(date);
long ms = timeline.toMillisecond(value);
Calendar cal2 = Calendar.getInstance(Locale.UK);
cal2.setTime(new Date(ms));
Date reverted = cal2.getTime();
Calendar expectedReverted = Calendar.getInstance(Locale.UK);
expectedReverted.set(Calendar.YEAR, 2004);
expectedReverted.set(Calendar.MONTH, Calendar.MARCH);
expectedReverted.set(Calendar.DAY_OF_MONTH, 29);
expectedReverted.set(Calendar.HOUR_OF_DAY, 9);
expectedReverted.set(Calendar.MINUTE, 0);
expectedReverted.set(Calendar.SECOND, 0);
expectedReverted.set(Calendar.MILLISECOND, 0);
assertTrue(
"test6", value == (900000 * 34 * 2)
&& expectedReverted.getTime().getTime() == reverted.getTime()
);
TimeZone.setDefault(savedZone);
}
/**
* Some checks for the getFirstMillisecond() method.
*/
public void testGetFirstMillisecond() {
Locale saved = Locale.getDefault();
Locale.setDefault(Locale.UK);
TimeZone savedZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Hour h = new Hour(15, 1, 4, 2006);
assertEquals(1143900000000L, h.getFirstMillisecond());
Locale.setDefault(saved);
TimeZone.setDefault(savedZone);
}
/**
* sets a TimeZone represented by the supplied ID string into all
* of the parsers used by this server.
*
* @param serverTimeZone Time Id java.util.TimeZone id used by
* the ftp server. If null the client's local time zone is assumed.
*/
private void setServerTimeZone(String serverTimeZoneId) {
TimeZone serverTimeZone = TimeZone.getDefault();
if (serverTimeZoneId != null) {
serverTimeZone = TimeZone.getTimeZone(serverTimeZoneId);
}
this.defaultDateFormat.setTimeZone(serverTimeZone);
if (this.recentDateFormat != null) {
this.recentDateFormat.setTimeZone(serverTimeZone);
}
}
public static void main(String[] args) {
if (args.length == 1) {
duration = Math.max(10, Integer.parseInt(args[0]));
}
Locale savedLocale = Locale.getDefault();
TimeZone savedTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific"));
Locale.setDefault(Locale.US);
masterSdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
// Once it is used, DecimalFormat becomes not thread-safe.
Date d = masterSdf.parse(TIME_STRING);
new Bug6335238();
} catch (Exception e) {
System.err.println(e);
err = true;
} finally {
TimeZone.setDefault(savedTimeZone);
Locale.setDefault(savedLocale);
if (err) {
throw new RuntimeException("Failed: Multiple DateFormat instances didn't work correctly.");
} else {
System.out.println("Passed.");
}
}
}
/**
* Some checks for the getLastMillisecond() method.
*/
public void testGetLastMillisecond() {
Locale saved = Locale.getDefault();
Locale.setDefault(Locale.UK);
TimeZone savedZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Second s = new Second(1, 1, 1, 1, 1, 1970);
assertEquals(61999L, s.getLastMillisecond());
Locale.setDefault(saved);
TimeZone.setDefault(savedZone);
}
/**
* Some checks for the getLastMillisecond() method.
*/
public void testGetLastMillisecond() {
Locale saved = Locale.getDefault();
Locale.setDefault(Locale.UK);
TimeZone savedZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Year y = new Year(1970);
// TODO: Check this result...
assertEquals(31532399999L, y.getLastMillisecond());
Locale.setDefault(saved);
TimeZone.setDefault(savedZone);
}
/**
* Test 6 checks that 9am on Sunday 28 March 2004 converts to the timeline
* value and back again correctly. Note that Saturday and Sunday are
* excluded from the timeline, so we expect the value to map to 9am on
* Monday 29 March 2004. This is during daylight saving.
*/
@Test
public void test6() {
TimeZone savedZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Calendar cal = Calendar.getInstance(Locale.UK);
cal.set(Calendar.YEAR, 2004);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DAY_OF_MONTH, 28);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
SegmentedTimeline timeline = getTimeline();
long value = timeline.toTimelineValue(date);
long ms = timeline.toMillisecond(value);
Calendar cal2 = Calendar.getInstance(Locale.UK);
cal2.setTime(new Date(ms));
Date reverted = cal2.getTime();
Calendar expectedReverted = Calendar.getInstance(Locale.UK);
expectedReverted.set(Calendar.YEAR, 2004);
expectedReverted.set(Calendar.MONTH, Calendar.MARCH);
expectedReverted.set(Calendar.DAY_OF_MONTH, 29);
expectedReverted.set(Calendar.HOUR_OF_DAY, 9);
expectedReverted.set(Calendar.MINUTE, 0);
expectedReverted.set(Calendar.SECOND, 0);
expectedReverted.set(Calendar.MILLISECOND, 0);
assertTrue("test6", value == (900000 * 34 * 2)
&& expectedReverted.getTime().getTime() == reverted.getTime());
TimeZone.setDefault(savedZone);
}
/**
* Some checks for the getFirstMillisecond() method.
*/
@Test
public void testGetFirstMillisecond() {
Locale saved = Locale.getDefault();
Locale.setDefault(Locale.UK);
TimeZone savedZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Week w = new Week(3, 1970);
assertEquals(946800000L, w.getFirstMillisecond());
Locale.setDefault(saved);
TimeZone.setDefault(savedZone);
}
@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);
}
}
public static void main(String[] args) {
TimeZone UTC = TimeZone.getTimeZone("UTC");
TimeZone initTz = TimeZone.getDefault();
List<String> errors = new ArrayList<>();
try {
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
for (Locale locale : DateFormat.getAvailableLocales()) {
// exclude any locales which localize "UTC".
String utc = UTC.getDisplayName(false, SHORT, locale);
if (!"UTC".equals(utc)) {
System.out.println("Skipping " + locale + " due to localized UTC name: " + utc);
continue;
}
SimpleDateFormat fmt = new SimpleDateFormat("z", locale);
try {
Date date = fmt.parse("UTC");
// Parsed one may not exactly be UTC. Universal, UCT, etc. are equivalents.
if (!fmt.getTimeZone().getID().matches("(Etc/)?(UTC|Universal|UCT|Zulu)")) {
errors.add("timezone: " + fmt.getTimeZone().getID()
+ ", locale: " + locale);
}
} catch (ParseException e) {
errors.add("parse exception: " + e + ", locale: " + locale);
}
}
} finally {
// Restore the default time zone
TimeZone.setDefault(initTz);
}
if (!errors.isEmpty()) {
System.out.println("Got unexpected results:");
for (String s : errors) {
System.out.println(" " + s);
}
throw new RuntimeException("Test failed.");
} else {
System.out.println("Test passed.");
}
}
@Override
public TimeZone getTimeZone()
{
return TimeZone.getDefault();
}
public static void main(String[] args) {
TimeZone defaultTimeZone = TimeZone.getDefault();
int errors = 0;
Calendar cal = new GregorianCalendar(BEGIN_YEAR, MARCH, 1);
String[] tzids = TimeZone.getAvailableIDs();
try {
for (String id : tzids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (!tz.useDaylightTime()) {
continue;
}
TimeZone.setDefault(tz);
dateloop:
// Use future dates because sun.util.calendar.ZoneInfo
// delegates offset transition calculations to a SimpleTimeZone
// (after 2038 as of JDK7).
for (int year = BEGIN_YEAR; year < END_YEAR; year++) {
for (int month = MARCH; month <= NOVEMBER; month++) {
cal.set(year, month, 1, 15, 0, 0);
int maxDom = cal.getActualMaximum(DAY_OF_MONTH);
for (int dom = 1; dom <= maxDom; dom++) {
Date date = new Date(year - 1900, month, dom);
if (date.getYear()+1900 != year
|| date.getMonth() != month
|| date.getDate() != dom) {
System.err.printf("%s: got %04d-%02d-%02d, expected %04d-%02d-%02d%n",
id,
date.getYear() + 1900,
date.getMonth() + 1,
date.getDate(),
year,
month + 1,
dom);
errors++;
break dateloop;
}
}
}
}
}
} finally {
// Restore the default TimeZone.
TimeZone.setDefault(defaultTimeZone);
}
if (errors > 0) {
throw new RuntimeException("Transition test failed");
}
}
/**
* 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;
}
/**
* Constructs a new instance, based on the supplied date/time and
* the default time zone.
*
* @param time the date-time (<code>null</code> not permitted).
*
* @see #Hour(Date, TimeZone)
*/
public Hour(Date time) {
// defer argument checking...
this(time, TimeZone.getDefault(), Locale.getDefault());
}
/**
* 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;
}
/**
* Constructs a new instance from the specified date/time and the default
* time zone..
*
* @param time the time (<code>null</code> not permitted).
*
* @see #Second(Date, TimeZone)
*/
public Second(Date time) {
this(time, TimeZone.getDefault(), Locale.getDefault());
}
/**
* Constructor which accepts a date value and a precision value. Valid precisions values for this type are:
* <ul>
* <li>{@link TemporalPrecisionEnum#YEAR}
* <li>{@link TemporalPrecisionEnum#MONTH}
* <li>{@link TemporalPrecisionEnum#DAY}
* <li>{@link TemporalPrecisionEnum#SECOND}
* <li>{@link TemporalPrecisionEnum#MILLI}
* </ul>
*
* @throws DataFormatException
* If the specified precision is not allowed for this type
*/
public DateTimeType(Date theDate, TemporalPrecisionEnum thePrecision) {
super(theDate, thePrecision, TimeZone.getDefault());
}