下面列出了java.util.TimeZone#equals ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected String formatWithTimeZone(
String template,
Object[] arguments,
Locale locale,
TimeZone timezone)
{
MessageFormat mf = new MessageFormat(" ");
mf.setLocale(locale);
mf.applyPattern(template);
if (!timezone.equals(TimeZone.getDefault()))
{
Format[] formats = mf.getFormats();
for (int i = 0; i < formats.length; i++)
{
if (formats[i] instanceof DateFormat)
{
DateFormat temp = (DateFormat) formats[i];
temp.setTimeZone(timezone);
mf.setFormat(i,temp);
}
}
}
return mf.format(arguments);
}
public static void main(String[] args) {
int errors = 0;
String[] ZONES = { "GMT", "MET", "IST" };
for (String id : ZONES) {
TimeZone zone = TimeZone.getTimeZone(id);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream ostream = new ObjectOutputStream(baos)) {
ostream.writeObject(zone);
}
try (ObjectInputStream istream
= new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
if (!zone.equals(istream.readObject())) {
errors++;
System.out.println("Time zone " + id + " are not equal to serialized/deserialized one.");
} else {
System.out.println("Time zone " + id + " ok.");
}
}
} catch (IOException | ClassNotFoundException e) {
errors++;
System.out.println(e);
}
}
if (errors > 0) {
throw new RuntimeException("test failed");
}
}
public static void main(String[] args) {
TimeZone defaultZone = TimeZone.getDefault();
// Make sure that TimeZone.setDefault works for trusted code
TimeZone.setDefault(NOWHERE);
if (!NOWHERE.equals(TimeZone.getDefault())) {
new RuntimeException("TimeZone.setDefault doesn't work for trusted code.");
}
// Restore defaultZone
TimeZone.setDefault(defaultZone);
if (!defaultZone.equals(TimeZone.getDefault())) {
new RuntimeException("TimeZone.setDefault doesn't restore defaultZone.");
}
// Install a SecurityManager.
System.setSecurityManager(new SecurityManager());
try {
TimeZone.setDefault(NOWHERE);
throw new RuntimeException("TimeZone.setDefault doesn't throw a SecurityException.");
} catch (SecurityException se) {
// OK
}
TimeZone tz = TimeZone.getDefault();
if (!defaultZone.equals(tz)) {
throw new RuntimeException("Default TimeZone changed: " + tz);
}
}
public static void main(String[] args) {
int errors = 0;
String[] ZONES = { "GMT", "MET", "IST" };
for (String id : ZONES) {
TimeZone zone = TimeZone.getTimeZone(id);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream ostream = new ObjectOutputStream(baos)) {
ostream.writeObject(zone);
}
try (ObjectInputStream istream
= new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
if (!zone.equals(istream.readObject())) {
errors++;
System.out.println("Time zone " + id + " are not equal to serialized/deserialized one.");
} else {
System.out.println("Time zone " + id + " ok.");
}
}
} catch (IOException | ClassNotFoundException e) {
errors++;
System.out.println(e);
}
}
if (errors > 0) {
throw new RuntimeException("test failed");
}
}
/**
* Returns a version of this formatter customized to the provided time zone.
*/
public DateFormatter withTimeZone(TimeZone tz) {
if (!tz.equals(timeZone)) {
return new YMDDateFormatter(requestedFields, localeName, tz);
}
return this;
}
public static void main(String[] args) {
TimeZone defaultZone = TimeZone.getDefault();
// Make sure that TimeZone.setDefault works for trusted code
TimeZone.setDefault(NOWHERE);
if (!NOWHERE.equals(TimeZone.getDefault())) {
new RuntimeException("TimeZone.setDefault doesn't work for trusted code.");
}
// Restore defaultZone
TimeZone.setDefault(defaultZone);
if (!defaultZone.equals(TimeZone.getDefault())) {
new RuntimeException("TimeZone.setDefault doesn't restore defaultZone.");
}
// Install a SecurityManager.
System.setSecurityManager(new SecurityManager());
try {
TimeZone.setDefault(NOWHERE);
throw new RuntimeException("TimeZone.setDefault doesn't throw a SecurityException.");
} catch (SecurityException se) {
// OK
}
TimeZone tz = TimeZone.getDefault();
if (!defaultZone.equals(tz)) {
throw new RuntimeException("Default TimeZone changed: " + tz);
}
}
public static void main(String[] args) {
TimeZone defaultZone = TimeZone.getDefault();
// Make sure that TimeZone.setDefault works for trusted code
TimeZone.setDefault(NOWHERE);
if (!NOWHERE.equals(TimeZone.getDefault())) {
new RuntimeException("TimeZone.setDefault doesn't work for trusted code.");
}
// Restore defaultZone
TimeZone.setDefault(defaultZone);
if (!defaultZone.equals(TimeZone.getDefault())) {
new RuntimeException("TimeZone.setDefault doesn't restore defaultZone.");
}
// Install a SecurityManager.
System.setSecurityManager(new SecurityManager());
try {
TimeZone.setDefault(NOWHERE);
throw new RuntimeException("TimeZone.setDefault doesn't throw a SecurityException.");
} catch (SecurityException se) {
// OK
}
TimeZone tz = TimeZone.getDefault();
if (!defaultZone.equals(tz)) {
throw new RuntimeException("Default TimeZone changed: " + tz);
}
}
/**
* Set the name of the locale that will be used when
* creating new formatters.
*
* @param timeZone The time zone to use.
* @return this BasicDurationFormatterFactory
*/
@Override
public DurationFormatterFactory setTimeZone(TimeZone timeZone) {
if (!timeZone.equals(this.timeZone)) {
this.timeZone = timeZone;
if (builder != null) {
builder = builder.withTimeZone(timeZone);
}
reset();
}
return this;
}
@Provides
TimeZone provideTimeZone() {
TimeZone timeZone = TimeZone.getTimeZone(options.cronTimezone);
TimeZone systemTimeZone = TimeZone.getDefault();
if (!timeZone.equals(systemTimeZone)) {
LOG.warn("Cron schedules are configured to fire according to timezone "
+ timeZone.getDisplayName()
+ " but system timezone is set to "
+ systemTimeZone.getDisplayName());
}
return timeZone;
}
public static void main(String[] args) {
TimeZone defaultZone = TimeZone.getDefault();
// Make sure that TimeZone.setDefault works for trusted code
TimeZone.setDefault(NOWHERE);
if (!NOWHERE.equals(TimeZone.getDefault())) {
new RuntimeException("TimeZone.setDefault doesn't work for trusted code.");
}
// Restore defaultZone
TimeZone.setDefault(defaultZone);
if (!defaultZone.equals(TimeZone.getDefault())) {
new RuntimeException("TimeZone.setDefault doesn't restore defaultZone.");
}
// Install a SecurityManager.
System.setSecurityManager(new SecurityManager());
try {
TimeZone.setDefault(NOWHERE);
throw new RuntimeException("TimeZone.setDefault doesn't throw a SecurityException.");
} catch (SecurityException se) {
// OK
}
TimeZone tz = TimeZone.getDefault();
if (!defaultZone.equals(tz)) {
throw new RuntimeException("Default TimeZone changed: " + tz);
}
}
/**
* find time zone 'text' matched zoneStrings and set to internal
* calendar.
*/
private int subParseZoneString(String text, int start, CalendarBuilder calb) {
boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
TimeZone currentTimeZone = getTimeZone();
// At this point, check for named time zones by looking through
// the locale data from the TimeZoneNames strings.
// Want to be able to parse both short and long forms.
int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
TimeZone tz = null;
String[][] zoneStrings = formatData.getZoneStringsWrapper();
String[] zoneNames = null;
int nameIndex = 0;
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
// Check if the standard name (abbr) and the daylight name are the same.
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
if (tz == null) {
zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
}
if (tz == null) {
int len = zoneStrings.length;
for (int i = 0; i < len; i++) {
zoneNames = zoneStrings[i];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
break;
}
}
}
if (tz != null) { // Matched any ?
if (!tz.equals(currentTimeZone)) {
setTimeZone(tz);
}
// If the time zone matched uses the same name
// (abbreviation) for both standard and daylight time,
// let the time zone in the Calendar decide which one.
//
// Also if tz.getDSTSaving() returns 0 for DST, use tz to
// determine the local time. (6645292)
int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
}
return (start + zoneNames[nameIndex].length());
}
return 0;
}
/**
* find time zone 'text' matched zoneStrings and set to internal
* calendar.
*/
private int subParseZoneString(String text, int start, CalendarBuilder calb) {
boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
TimeZone currentTimeZone = getTimeZone();
// At this point, check for named time zones by looking through
// the locale data from the TimeZoneNames strings.
// Want to be able to parse both short and long forms.
int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
TimeZone tz = null;
String[][] zoneStrings = formatData.getZoneStringsWrapper();
String[] zoneNames = null;
int nameIndex = 0;
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
// Check if the standard name (abbr) and the daylight name are the same.
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
if (tz == null) {
zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
}
if (tz == null) {
int len = zoneStrings.length;
for (int i = 0; i < len; i++) {
zoneNames = zoneStrings[i];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
break;
}
}
}
if (tz != null) { // Matched any ?
if (!tz.equals(currentTimeZone)) {
setTimeZone(tz);
}
// If the time zone matched uses the same name
// (abbreviation) for both standard and daylight time,
// let the time zone in the Calendar decide which one.
//
// Also if tz.getDSTSaving() returns 0 for DST, use tz to
// determine the local time. (6645292)
int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
}
return (start + zoneNames[nameIndex].length());
}
return -start;
}
private static boolean isTimeSettingChanged() {
TimeZone currentTZ = TimeZone.getDefault();
boolean currentDST = currentTZ.inDaylightTime(new Date());
return (!currentTZ.equals(TZ) || currentDST != DST);
}
/**
* find time zone 'text' matched zoneStrings and set to internal
* calendar.
*/
private int subParseZoneString(String text, int start, CalendarBuilder calb) {
boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
TimeZone currentTimeZone = getTimeZone();
// At this point, check for named time zones by looking through
// the locale data from the TimeZoneNames strings.
// Want to be able to parse both short and long forms.
int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
TimeZone tz = null;
String[][] zoneStrings = formatData.getZoneStringsWrapper();
String[] zoneNames = null;
int nameIndex = 0;
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
// Check if the standard name (abbr) and the daylight name are the same.
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
if (tz == null) {
zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
}
if (tz == null) {
int len = zoneStrings.length;
for (int i = 0; i < len; i++) {
zoneNames = zoneStrings[i];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
break;
}
}
}
if (tz != null) { // Matched any ?
if (!tz.equals(currentTimeZone)) {
setTimeZone(tz);
}
// If the time zone matched uses the same name
// (abbreviation) for both standard and daylight time,
// let the time zone in the Calendar decide which one.
//
// Also if tz.getDSTSaving() returns 0 for DST, use tz to
// determine the local time. (6645292)
int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
}
return (start + zoneNames[nameIndex].length());
}
return -start;
}
/**
* find time zone 'text' matched zoneStrings and set to internal
* calendar.
*/
private int subParseZoneString(String text, int start, CalendarBuilder calb) {
boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
TimeZone currentTimeZone = getTimeZone();
// At this point, check for named time zones by looking through
// the locale data from the TimeZoneNames strings.
// Want to be able to parse both short and long forms.
int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
TimeZone tz = null;
String[][] zoneStrings = formatData.getZoneStringsWrapper();
String[] zoneNames = null;
int nameIndex = 0;
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
// Check if the standard name (abbr) and the daylight name are the same.
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
if (tz == null) {
zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
}
if (tz == null) {
int len = zoneStrings.length;
for (int i = 0; i < len; i++) {
zoneNames = zoneStrings[i];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
break;
}
}
}
if (tz != null) { // Matched any ?
if (!tz.equals(currentTimeZone)) {
setTimeZone(tz);
}
// If the time zone matched uses the same name
// (abbreviation) for both standard and daylight time,
// let the time zone in the Calendar decide which one.
//
// Also if tz.getDSTSaving() returns 0 for DST, use tz to
// determine the local time. (6645292)
int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
}
return (start + zoneNames[nameIndex].length());
}
return -start;
}
public static void main(String[] args) throws Throwable {
int N = 10000;
long t1970 = new java.util.Date(70, 0, 01).getTime();
Random r = new Random();
for (int i = 0; i < N; i++) {
int days = r.nextInt(50) * 365 + r.nextInt(365);
long secs = t1970 + days * 86400 + r.nextInt(86400);
int nanos = r.nextInt(NANOS_PER_SECOND);
int nanos_ms = nanos / 1000000 * 1000000; // millis precision
long millis = secs * 1000 + r.nextInt(1000);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
Instant inst = Instant.ofEpochSecond(secs, nanos);
Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
///////////// java.util.Date /////////////////////////
Date jud = new java.util.Date(millis);
Instant inst0 = jud.toInstant();
if (jud.getTime() != inst0.toEpochMilli() ||
!jud.equals(Date.from(inst0))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
}
// roundtrip only with millis precision
Date jud0 = Date.from(inst_ms);
if (jud0.getTime() != inst_ms.toEpochMilli() ||
!inst_ms.equals(jud0.toInstant())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
}
//////////// java.util.GregorianCalendar /////////////
GregorianCalendar cal = new GregorianCalendar();
// non-roundtrip of tz name between j.u.tz and j.t.zid
cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
cal.setTimeInMillis(millis);
ZonedDateTime zdt0 = cal.toZonedDateTime();
if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() ||
!cal.equals(GregorianCalendar.from(zdt0))) {
System.out.println("cal:" + cal);
System.out.println("zdt:" + zdt0);
System.out.println("calNew:" + GregorianCalendar.from(zdt0));
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
}
inst0 = cal.toInstant();
if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: gcal -> zdt");
}
ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
GregorianCalendar cal0 = GregorianCalendar.from(zdt);
if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() ||
!zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
}
}
///////////// java.util.TimeZone /////////////////////////
for (String zidStr : TimeZone.getAvailableIDs()) {
// TBD: tzdt intergration
if (zidStr.startsWith("SystemV") ||
zidStr.contains("Riyadh8") ||
zidStr.equals("US/Pacific-New") ||
zidStr.equals("EST") ||
zidStr.equals("HST") ||
zidStr.equals("MST")) {
continue;
}
ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
}
TimeZone tz = TimeZone.getTimeZone(zidStr);
// no round-trip for alias and "GMT"
if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) &&
!ZoneId.SHORT_IDS.containsKey(zidStr) &&
!zidStr.startsWith("GMT")) {
throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
}
}
System.out.println("Passed!");
}
/**
* find time zone 'text' matched zoneStrings and set to internal
* calendar.
*/
private int subParseZoneString(String text, int start, CalendarBuilder calb) {
boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
TimeZone currentTimeZone = getTimeZone();
// At this point, check for named time zones by looking through
// the locale data from the TimeZoneNames strings.
// Want to be able to parse both short and long forms.
int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
TimeZone tz = null;
String[][] zoneStrings = formatData.getZoneStringsWrapper();
String[] zoneNames = null;
int nameIndex = 0;
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
// Check if the standard name (abbr) and the daylight name are the same.
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
if (tz == null) {
zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
}
if (tz == null) {
int len = zoneStrings.length;
for (int i = 0; i < len; i++) {
zoneNames = zoneStrings[i];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
break;
}
}
}
if (tz != null) { // Matched any ?
if (!tz.equals(currentTimeZone)) {
setTimeZone(tz);
}
// If the time zone matched uses the same name
// (abbreviation) for both standard and daylight time,
// let the time zone in the Calendar decide which one.
//
// Also if tz.getDSTSaving() returns 0 for DST, use tz to
// determine the local time. (6645292)
int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
}
return (start + zoneNames[nameIndex].length());
}
return -start;
}
/**
* Returns a string representation of the FTPFile information.
* This currently mimics the Unix listing format.
* This method allows the Calendar time zone to be overridden.
* <p>
* Note: if the instance is not valid {@link #isValid()}, no useful
* information can be returned. In this case, use {@link #getRawListing()}
* instead.
*
* @param timezone the timezone to use for displaying the time stamp
* If {@code null}, then use the Calendar entry timezone
* @return A string representation of the FTPFile information.
* @since 3.4
*/
public String toFormattedString(final String timezone) {
if (!isValid()) {
return "[Invalid: could not parse file entry]";
}
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
sb.append(formatType());
sb.append(permissionToString(USER_ACCESS));
sb.append(permissionToString(GROUP_ACCESS));
sb.append(permissionToString(WORLD_ACCESS));
fmt.format(" %4d", Integer.valueOf(getHardLinkCount()));
fmt.format(" %-8s %-8s", getUser(), getGroup());
fmt.format(" %8d", Long.valueOf(getSize()));
Calendar timestamp = getTimestamp();
if (timestamp != null) {
if (timezone != null) {
TimeZone newZone = TimeZone.getTimeZone(timezone);
if (!newZone.equals(timestamp.getTimeZone())) {
Date original = timestamp.getTime();
Calendar newStamp = Calendar.getInstance(newZone);
newStamp.setTime(original);
timestamp = newStamp;
}
}
fmt.format(" %1$tY-%1$tm-%1$td", timestamp);
// Only display time units if they are present
if (timestamp.isSet(Calendar.HOUR_OF_DAY)) {
fmt.format(" %1$tH", timestamp);
if (timestamp.isSet(Calendar.MINUTE)) {
fmt.format(":%1$tM", timestamp);
if (timestamp.isSet(Calendar.SECOND)) {
fmt.format(":%1$tS", timestamp);
if (timestamp.isSet(Calendar.MILLISECOND)) {
fmt.format(".%1$tL", timestamp);
}
}
}
fmt.format(" %1$tZ", timestamp);
}
}
sb.append(' ');
sb.append(getName());
fmt.close();
return sb.toString();
}
public static void main(String[] args) throws Throwable {
int N = 10000;
@SuppressWarnings("deprecation")
long t1970 = new java.util.Date(70, 0, 01).getTime();
Random r = new Random();
for (int i = 0; i < N; i++) {
int days = r.nextInt(50) * 365 + r.nextInt(365);
long secs = t1970 + days * 86400 + r.nextInt(86400);
int nanos = r.nextInt(NANOS_PER_SECOND);
int nanos_ms = nanos / 1000000 * 1000000; // millis precision
long millis = secs * 1000 + r.nextInt(1000);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
Instant inst = Instant.ofEpochSecond(secs, nanos);
Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
///////////// java.util.Date /////////////////////////
Date jud = new java.util.Date(millis);
Instant inst0 = jud.toInstant();
if (jud.getTime() != inst0.toEpochMilli()
|| !jud.equals(Date.from(inst0))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
}
// roundtrip only with millis precision
Date jud0 = Date.from(inst_ms);
if (jud0.getTime() != inst_ms.toEpochMilli()
|| !inst_ms.equals(jud0.toInstant())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
}
//////////// java.util.GregorianCalendar /////////////
GregorianCalendar cal = new GregorianCalendar();
// non-roundtrip of tz name between j.u.tz and j.t.zid
cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
cal.setTimeInMillis(millis);
ZonedDateTime zdt0 = cal.toZonedDateTime();
if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli()
|| !cal.equals(GregorianCalendar.from(zdt0))) {
System.out.println("cal:" + cal);
System.out.println("zdt:" + zdt0);
System.out.println("calNew:" + GregorianCalendar.from(zdt0));
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
}
inst0 = cal.toInstant();
if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: gcal -> zdt");
}
ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
GregorianCalendar cal0 = GregorianCalendar.from(zdt);
if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis()
|| !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
}
}
///////////// java.util.TimeZone /////////////////////////
for (String zidStr : TimeZone.getAvailableIDs()) {
// TBD: tzdt intergration
if (zidStr.startsWith("SystemV")
|| zidStr.contains("Riyadh8")
|| zidStr.equals("US/Pacific-New")
|| zidStr.equals("EST")
|| zidStr.equals("HST")
|| zidStr.equals("MST")) {
continue;
}
ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
}
TimeZone tz = TimeZone.getTimeZone(zidStr);
// no round-trip for alias and "GMT"
if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId()))
&& !ZoneId.SHORT_IDS.containsKey(zidStr)
&& !zidStr.startsWith("GMT")) {
throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
}
}
System.out.println("Passed!");
}
/**
* find time zone 'text' matched zoneStrings and set to internal
* calendar.
*/
private int subParseZoneString(String text, int start, CalendarBuilder calb) {
boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
TimeZone currentTimeZone = getTimeZone();
// At this point, check for named time zones by looking through
// the locale data from the TimeZoneNames strings.
// Want to be able to parse both short and long forms.
int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
TimeZone tz = null;
String[][] zoneStrings = formatData.getZoneStringsWrapper();
String[] zoneNames = null;
int nameIndex = 0;
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
// Check if the standard name (abbr) and the daylight name are the same.
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
if (tz == null) {
zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
if (zoneIndex != -1) {
zoneNames = zoneStrings[zoneIndex];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
}
}
}
if (tz == null) {
int len = zoneStrings.length;
for (int i = 0; i < len; i++) {
zoneNames = zoneStrings[i];
if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
if (nameIndex <= 2) {
useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
}
tz = TimeZone.getTimeZone(zoneNames[0]);
break;
}
}
}
if (tz != null) { // Matched any ?
if (!tz.equals(currentTimeZone)) {
setTimeZone(tz);
}
// If the time zone matched uses the same name
// (abbreviation) for both standard and daylight time,
// let the time zone in the Calendar decide which one.
//
// Also if tz.getDSTSaving() returns 0 for DST, use tz to
// determine the local time. (6645292)
int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
}
return (start + zoneNames[nameIndex].length());
}
return 0;
}