@Test public void testCompareCETnPST() { String stCET = "CET"; TimeZone tzCET = TimeZone.getTimeZone(stCET); String stPST = "PST"; TimeZone tzPST = TimeZone.getTimeZone(stPST); Date today = new Date(); long offSetCET = tzCET.getOffset(today.getTime()); long offSetPST = tzPST.getOffset(today.getTime()); displayTZ(tzCET, tzPST); m_logger.info( "tzCET info: " + tzCET.getDisplayName() + "/" + tzCET.getDSTSavings() + "/" + tzCET.getOffset(today.getTime())); m_logger.info( "tzPST info: " + tzPST.getDisplayName() + "/" + tzPST.getDSTSavings() + "/" + tzPST.getOffset(today.getTime())); assertTrue(true); }
/** * 根据不同时区,转换时间 2014年7月31日 * * @param time * @return */ public static Date transformTime(Date date, TimeZone oldZone, TimeZone newZone) { Date finalDate = null; if (date != null) { int timeOffset = oldZone.getOffset(date.getTime()) - newZone.getOffset(date.getTime()); finalDate = new Date(date.getTime() - timeOffset); } return finalDate; }
private String getTimeStamp() { GregorianCalendar cal = new GregorianCalendar(); TimeZone tz = TimeZone.getTimeZone("EST5EDT"); TimeZone calTz = cal.getTimeZone(); long millis = cal.getTimeInMillis(); int differenceTz = calTz.getOffset(millis) - tz.getOffset(millis); millis = cal.getTimeInMillis() - (long) differenceTz; return DATE_FORMAT.format(new Date(millis)); }
/** * Converts a Date in default time zone to client's time zone. * * @param inputDate a date in the default time zone * @return a date in the client time zone */ private Date convertDateToClientTimeZone(Date inputDate) { Calendar c = Calendar.getInstance(locale); c.setTime(inputDate); TimeZone clientZone = timeZoneTracker.getClientTimeZone(); TimeZone defaultZone = TimeZone.getDefault(); long now = System.currentTimeMillis(); int offset = defaultZone.getOffset(now) - clientZone.getOffset(now); c.add(Calendar.MILLISECOND, offset); return c.getTime(); }
protected static String formatTimezone(TimeZone tz) { Date now = new Date(); float offset = (float) tz.getOffset(now.getTime()) / ONE_HOUR_IN_MS; int hours = (int) offset; int minutes = (offset - hours == 0) ? 0 : 30; return String.format("%d.%02d", hours, minutes); }
DataContextImpl(OptiqConnectionImpl connection, List<Object> parameterValues) { this.queryProvider = connection; this.typeFactory = connection.getTypeFactory(); this.rootSchema = connection.rootSchema; // Store the time at which the query started executing. The SQL // standard says that functions such as CURRENT_TIMESTAMP return the // same value throughout the query. final long time = System.currentTimeMillis(); final TimeZone timeZone = connection.getTimeZone(); final long localOffset = timeZone.getOffset(time); final long currentOffset = localOffset; ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder(); builder .put("utcTimestamp", time) .put("currentTimestamp", time + currentOffset) .put("localTimestamp", time + localOffset) .put("timeZone", timeZone); for (Ord<Object> value : Ord.zip(parameterValues)) { Object e = value.e; if (e == null) { e = AvaticaParameter.DUMMY_VALUE; } builder.put("?" + value.i, e); } map = builder.build(); }
/** Sets the time in milliseconds since the epoch and calculate the internal variables. */ public void setLocalTime(long time) { // If this is a local time zone date, just set the time if (_timeZone != _gmtTimeZone) { calculateSplit(time); } // If this is a GMT date, convert from local to GMT else { calculateSplit(time - _localTimeZone.getRawOffset()); try { long offset = _localTimeZone.getOffset( GregorianCalendar.AD, (int) _year, (int) _month, (int) _dayOfMonth + 1, getDayOfWeek(), (int) _timeOfDay); calculateSplit(time - offset); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } }
public static String date2UTC(Date dateTime, TimeZone timeZone) throws UtilitiesException { try { DecimalFormat twoDigits; String utc; String sign; int hours; int minutes; SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); dateFormatter.setLenient(false); dateFormatter.setTimeZone(timeZone); twoDigits = new DecimalFormat("00"); utc = dateFormatter.format(dateTime); int tzOffset = timeZone.getOffset(dateTime.getTime()); sign = "+"; if (tzOffset < 0) { sign = "-"; tzOffset = -tzOffset; } hours = tzOffset / 0x36ee80; minutes = (tzOffset % 0x36ee80) / 60000; return (new StringBuffer(utc.length() + 7)) .append(utc) .append(sign) .append(twoDigits.format(hours)) .append(":") .append(twoDigits.format(minutes)) .toString(); } catch (Exception ex) { throw new hk.hku.cecid.piazza.commons.util.UtilitiesException(ex); } }
public TimeZoneRow(String id, String name) { mId = id; TimeZone tz = TimeZone.getTimeZone(id); boolean useDaylightTime = tz.useDaylightTime(); mOffset = tz.getOffset(mTime); mDisplayName = buildGmtDisplayName(name, useDaylightTime); }
/** * Get a DICOM format {@link java.lang.String String} time zone from a Java {@link * java.util.TimeZone TimeZone} on a particular Java {@link java.util.Date Date} . * * <p>E.g. from +0500 or -0700, the last component of a DateTime attribute value, or the value of * the DICOM attribute TimezoneOffsetFromUTC. * * @param javaTimeZone the {@link java.util.TimeZone TimeZone} time zone * @param javaDate the {@link java.util.Date Date} used to establish whether daylight savings is * in effect or not * @return a DICOM format {@link java.lang.String String} time zone representing the supplied time * zone on the supplied date */ public static String getTimeZone(java.util.TimeZone javaTimeZone, java.util.Date javaDate) { // System.err.println("DateTimeAttribute.getTimeZone(): javaTimeZone = "+javaTimeZone); // System.err.println("DateTimeAttribute.getTimeZone(): javaDate = "+javaDate); int offset = javaTimeZone.getOffset( javaDate .getTime()); // returns the amount of time in milliseconds to add to UTC to get // local time boolean isNegative = false; if (offset < 0) { isNegative = true; offset = -offset; } int offsetTotalMinutes = offset / 1000 / 60; int offsetHoursPart = offsetTotalMinutes / 60; int offsetMinutesPart = offsetTotalMinutes % 60; String tzInDICOMFormat = (isNegative ? "-" : "+") + (offsetHoursPart > 9 ? "" : "0") + offsetHoursPart + (offsetMinutesPart > 9 ? "" : "0") + offsetMinutesPart; // System.err.println("DateTimeAttribute.getTimeZone(): tzInDICOMFormat = "+tzInDICOMFormat); return tzInDICOMFormat; }
/** * Construct a PersonIdent from simple data * * @param aName * @param aEmailAddress * @param aWhen local time stamp * @param aTZ time zone */ public PersonIdent( final String aName, final String aEmailAddress, final Date aWhen, final TimeZone aTZ) { name = aName; emailAddress = aEmailAddress; when = aWhen.getTime(); tzOffset = aTZ.getOffset(when) / (60 * 1000); }
// @Ignore @Test public void allTimeZoneTest() { String[] tzIds = TimeZone.getAvailableIDs(); System.out.printf( "NUM) %32s, %5s \t,%15s\t,%15s,%6s\n", "Time Zone", "inDST", "offset", "DSTSavings", "useDST"); for (int i = 0; i < tzIds.length; i++) { String string = tzIds[i]; TimeZone timezone = TimeZone.getTimeZone(string); Date date = new Date(); // System.out.println(i + ") " + timezone.getID() + ", offset " + // timezone.getOffset(date.getTime()) + ", DSTSavings " + // timezone.getDSTSavings()); System.out.printf( "%3d) %32s, %5s \t,%15d\t,%15d,%6s\n", i, timezone.getID(), timezone.inDaylightTime(date), timezone.getOffset(date.getTime()), timezone.getDSTSavings(), timezone.useDaylightTime()); } assertTrue(true); }
@Test public void testTimeZoneCST() throws Exception { DateFormat df; Date d; TimeZone tzCST = TimeZone.getTimeZone("CST"); TimeZone tzPST = TimeZone.getTimeZone("PST"); // displayTZ(tzCST); String date = "02-11-2013:05:01:45"; df = new SimpleDateFormat("dd-MM-yyyy:HH:mm:SS"); d = (Date) df.parse(date); // Read more: // http://javarevisited.blogspot.com/2011/09/step-by-step-guide-to-convert-string-to.html#ixzz2a0OnXQoi System.out.println(date + "'s offset; " + d.getTimezoneOffset()); System.out.println("CST offset is" + tzCST.getOffset(d.getTime())); System.out.println("PST offset is" + tzPST.getOffset(d.getTime())); date = "03-11-2013:00:01:45"; d = (Date) df.parse(date); System.out.println(date + "'s offset; " + d.getTimezoneOffset()); System.out.println("CST offset is" + tzCST.getOffset(d.getTime())); System.out.println("PST offset is" + tzPST.getOffset(d.getTime())); date = "03-11-2013:01:01:45"; d = (Date) df.parse(date); System.out.println(date + "'s offset; " + d.getTimezoneOffset()); System.out.println("CST offset is" + tzCST.getOffset(d.getTime())); System.out.println("PST offset is" + tzPST.getOffset(d.getTime())); System.out.println( "The gap is" + (tzCST.getOffset(d.getTime()) - tzPST.getOffset(d.getTime()))); date = "03-11-2013:15:01:45"; d = (Date) df.parse(date); System.out.println(date + "'s offset; " + d.getTimezoneOffset()); System.out.println("CST offset is" + tzCST.getOffset(d.getTime())); System.out.println("PST offset is" + tzPST.getOffset(d.getTime())); assertTrue(true); }
public static String format(Date paramDate, boolean paramBoolean, TimeZone paramTimeZone) { GregorianCalendar localGregorianCalendar = new GregorianCalendar(paramTimeZone, Locale.US); localGregorianCalendar.setTime(paramDate); int i = "yyyy-MM-ddThh:mm:ss".length(); int j; int m; label56: StringBuilder localStringBuilder; char c; if (paramBoolean) { j = ".sss".length(); int k = i + j; if (paramTimeZone.getRawOffset() != 0) break label335; m = "Z".length(); localStringBuilder = new StringBuilder(k + m); padInt(localStringBuilder, localGregorianCalendar.get(1), "yyyy".length()); localStringBuilder.append('-'); padInt(localStringBuilder, 1 + localGregorianCalendar.get(2), "MM".length()); localStringBuilder.append('-'); padInt(localStringBuilder, localGregorianCalendar.get(5), "dd".length()); localStringBuilder.append('T'); padInt(localStringBuilder, localGregorianCalendar.get(11), "hh".length()); localStringBuilder.append(':'); padInt(localStringBuilder, localGregorianCalendar.get(12), "mm".length()); localStringBuilder.append(':'); padInt(localStringBuilder, localGregorianCalendar.get(13), "ss".length()); if (paramBoolean) { localStringBuilder.append('.'); padInt(localStringBuilder, localGregorianCalendar.get(14), "sss".length()); } int n = paramTimeZone.getOffset(localGregorianCalendar.getTimeInMillis()); if (n == 0) break label352; int i1 = Math.abs(n / 60000 / 60); int i2 = Math.abs(n / 60000 % 60); if (n >= 0) break label345; c = '-'; label283: localStringBuilder.append(c); padInt(localStringBuilder, i1, "hh".length()); localStringBuilder.append(':'); padInt(localStringBuilder, i2, "mm".length()); } while (true) { return localStringBuilder.toString(); j = 0; break; label335: m = "+hh:mm".length(); break label56; label345: c = '+'; break label283; label352: localStringBuilder.append('Z'); } }
public void setTimeZone(TimeZone timeZone) { Calendar calendar = Calendar.getInstance(timeZone); calendar.setTime(startTime.getTime()); startTime = calendar; calendar = Calendar.getInstance(timeZone); calendar.setTime(endTime.getTime()); endTime = calendar; agencyTimeZoneOffset = timeZone.getOffset(startTime.getTimeInMillis()); }
/** * Construct a date from a Dublin Core value * * @param fromDC the date string, in ISO 8601 (no timezone, always use UTC/GMT) */ public DCDate(String fromDC) { super(); // An empty date is OK if ((fromDC == null) || fromDC.equals("")) { return; } // default granularity granularity = DateGran.TIME; Date date = tryParse(fullIso, fromDC); if (date == null) date = tryParse(fullIso2, fromDC); if (date == null) date = tryParse(fullIso3, fromDC); if (date == null) { // NOTE: move GMT date to local midnight when granularity is coarse date = tryParse(dateIso, fromDC); if (date != null) { long ldate = date.getTime(); date = new Date(ldate - localZone.getOffset(ldate)); granularity = DateGran.DAY; } } if (date == null) { // NOTE: move GMT date to local midnight when granularity is coarse date = tryParse(yearMonthIso, fromDC); if (date != null) { long ldate = date.getTime(); date = new Date(ldate - localZone.getOffset(ldate)); granularity = DateGran.MONTH; } } if (date == null) { // NOTE: move GMT date to local midnight when granularity is coarse date = tryParse(yearIso, fromDC); if (date != null) { long ldate = date.getTime(); date = new Date(ldate - localZone.getOffset(ldate)); granularity = DateGran.YEAR; } } if (date == null) log.warn("Mangled date: " + fromDC + " ..failed all attempts to parse as date."); else setTime(date); }
private static long getTimeZoneOffset(long time, TimeZone from, TimeZone to) { int fromOffset = from.getOffset(time); int toOffset = to.getOffset(time); int diff = 0; if (fromOffset >= 0) { if (toOffset > 0) { toOffset = -1 * toOffset; } else { toOffset = Math.abs(toOffset); } diff = (fromOffset + toOffset) * -1; } else { if (toOffset <= 0) { toOffset = -1 * Math.abs(toOffset); } diff = (Math.abs(fromOffset) + toOffset); } return diff; }
@Test public void convertDateTimeToMilliseconds() { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(2014, 1, 1, 1, 1, 1); final TimeZone timeZone = calendar.getTimeZone(); long offset = timeZone.getOffset(calendar.getTime().getTime()); Long correctResult = offset + calendar.getTime().getTime(); assertEquals( highchartSeriesUtil.convertDateTimeToMilliseconds(calendar.getTime()), correctResult); }
/** * Gets current time in the following format Month, Date, Hours, Minutes, Seconds, Millisecond. * * @return Current date. */ public String getCurrentTimeStampString() { java.util.Date date = new java.util.Date(); SimpleDateFormat sd = new SimpleDateFormat("MMddHHmmssSS"); TimeZone timeZone = TimeZone.getDefault(); Calendar cal = Calendar.getInstance(new SimpleTimeZone(timeZone.getOffset(date.getTime()), "GMT")); sd.setCalendar(cal); return sd.format(date); }
public long getPreviousFireTimeBefore(long beforeTime) { long returnTime = Long.MIN_VALUE; if (beforeTime > getStart().getTime()) { if (beforeTime > getEnd().getTime()) beforeTime = getEnd().getTime(); long lstart = getStart().getTime(); CompanyCalendar cal = new CompanyCalendar(); cal.setTimeInMillis(lstart); TimeZone timeZone = cal.getTimeZone(); int ofset = (timeZone.getOffset(lstart) - timeZone.getOffset( beforeTime)); // questo server per calcolare i millisecondi effettivi in caso di // ora legale long distInMillisec = beforeTime - lstart - ofset; long distInDays = distInMillisec / CompanyCalendar.MILLIS_IN_DAY; long distInYear = distInDays / 365; // non sbaglia il conto fino a che non sono passati 1460 anni if (distInYear > 0) { cal.add(Calendar.YEAR, (int) distInYear); distInDays -= (distInYear * 365); } int distInMonth = (int) distInDays / 29; // in un anno dividendo per 29 i giorni ottengo sempre il numero corretto di // mesi int freq = (this.getFreq() > 0 ? this.getFreq() : 1); int rep = distInMonth / freq; if (this.getRepeat() == 0 || rep <= (this.getRepeat() - 1)) { cal.add(Calendar.MONTH, rep * freq); long before; if (weekOfMonth > 0 && dayOfWeek > 0) { before = getDayInWeekInMonth(cal); if (before < beforeTime) returnTime = before; } else { before = getDayInMonthBefore(cal, beforeTime); if (before < beforeTime) returnTime = before; } } } return returnTime; }
/** @tests java.util.SimpleTimeZone#getOffset(int, int, int, int, int, int) */ public void test_getOffsetIIIIII() { // Test for method int java.util.SimpleTimeZone.getOffset(int, int, int, // int, int, int) TimeZone st1 = TimeZone.getTimeZone("EST"); assertTrue( "Incorrect offset returned", st1.getOffset(GregorianCalendar.AD, 1998, Calendar.NOVEMBER, 11, Calendar.WEDNESDAY, 0) == -(5 * 60 * 60 * 1000)); st1 = TimeZone.getTimeZone("EST"); assertEquals( "Incorrect offset returned", -(5 * 60 * 60 * 1000), st1.getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 11, Calendar.THURSDAY, 0)); // Regression for HARMONY-5459 st1 = (TimeZone) TimeZone.getDefault(); int fourHours = 4 * 60 * 60 * 1000; st1.setRawOffset(fourHours); assertEquals(fourHours, st1.getOffset(1, 2099, 01, 1, 5, 0)); }
/** * The date is converted to the following format: <code>sYYYY-MM-DDThh:mm:ss.sssTZD</code> where: * * <dl> * <dt>sYYYY * <dd>Four-digit year with optional leading positive (‘+’) or negative (‘-’) sign. 0000 , -0000 * and +0000 all indicate the year 1 BCE. –YYYY where YYYY is the number y indicates the * year (y+1) BCE. The absence of a sign or the presence of a positive sign indicates a year * CE. For example, -0054 would indicate the year 55 BCE, while +1969 and 1969 indicate the * year 1969 CE. * <dt>MM * <dd>Two-digit month (01 = January, etc.) * <dt>DD * <dd>Two-digit day of month (01 through 31) * <dt>hh * <dd>Two digits of hour (00 through 23, or 24 if mm is 00 and ss.sss is 00.000) * <dt>mm * <dd>Two digits of minute (00 through 59) * <dt>ss.sss * <dd>Seconds, to three decimal places (00.000 through 59.999 or 60.999 in the case of leap * seconds) * <dt>TZD * <dd>Time zone designator (either Z for Zulu, i.e. UTC, or +hh:mm or -hh:mm, i.e. an offset * from UTC) * </dl> * * <p>Note that the “T” separating the date from the time and the separators “-”and “:” appear * literally in the string. * * <p>This format is a subset of the format defined by ISO 8601:2004. If the DATE value cannot be * represented in this format a {@link ValueFormatException} is thrown. */ public String getString() { // determine era and adjust year if necessary int year = value.get(Calendar.YEAR); if (value.isSet(Calendar.ERA) && value.get(Calendar.ERA) == GregorianCalendar.BC) { // calculate year using astronomical system: // year n BCE => astronomical year - n + 1 year = 0 - year + 1; } // note that we cannot use java.text.SimpleDateFormat for // formatting because it can't handle years <= 0 and TZD's StringBuilder buf = new StringBuilder(32); // year ([-]YYYY) buf.append(XXXX_FORMAT.format(year)); buf.append('-'); // month (MM) buf.append(XX_FORMAT.format(value.get(Calendar.MONTH) + 1)); buf.append('-'); // day (DD) buf.append(XX_FORMAT.format(value.get(Calendar.DAY_OF_MONTH))); buf.append('T'); // hour (hh) buf.append(XX_FORMAT.format(value.get(Calendar.HOUR_OF_DAY))); buf.append(':'); // minute (mm) buf.append(XX_FORMAT.format(value.get(Calendar.MINUTE))); buf.append(':'); // second (ss) buf.append(XX_FORMAT.format(value.get(Calendar.SECOND))); buf.append('.'); // millisecond (SSS) buf.append(XXX_FORMAT.format(value.get(Calendar.MILLISECOND))); // time zone designator (Z or +00:00 or -00:00) TimeZone tz = value.getTimeZone(); // time zone offset (in minutes) from UTC (including daylight saving) int offset = tz.getOffset(value.getTimeInMillis()) / 1000 / 60; if (offset != 0) { int hours = Math.abs(offset / 60); int minutes = Math.abs(offset % 60); buf.append(offset < 0 ? '-' : '+'); buf.append(XX_FORMAT.format(hours)); buf.append(':'); buf.append(XX_FORMAT.format(minutes)); } else { buf.append('Z'); } return buf.toString(); }
/** * function to set up alarm flag * * @return */ private static void alarm_flag_setup( Context mContext, final long alarmTimeInMillis, Alarm alarm) { Calendar c = Calendar.getInstance(); c.set(2011, 0, 1, 0, 0, 0); Calendar to = Calendar.getInstance(); to.setTimeInMillis(alarmTimeInMillis); TimeZone zone = c.getTimeZone(); long dstOffset = zone.getOffset(alarmTimeInMillis); long startTimeInMillis = c.getTimeInMillis(); long dstAlarmTimeInMillis = alarmTimeInMillis - dstOffset; long timeDiffInMillis = dstAlarmTimeInMillis - startTimeInMillis; long timeDiffInSecs = timeDiffInMillis / 1000; // bug[20603] to resolve clock don't alarm on right time 2012.06.20 add begin String prfsName = mContext.getPackageName(); prfsName += "_preferences"; SharedPreferences prefs = mContext.getSharedPreferences(prfsName, Context.MODE_WORLD_READABLE); String snooze_duration = prefs.getString("snooze_duration", "10"); // bug[20603] to resolve clock don't alarm on right time 2012.06.20 add end Log.v("write " + String.valueOf(timeDiffInSecs) + " to" + ALARM_FLAG_FILE); if (ALARM_FLAG_FILE.exists()) { Log.v(ALARM_FLAG_FILE + " already exist, delete it"); try { ALARM_FLAG_FILE.delete(); Log.v(ALARM_FLAG_FILE + " delete before write success"); } catch (Exception e) { Log.v(ALARM_FLAG_FILE + " delete before write failed"); } } try { FileWriter command = new FileWriter(ALARM_FLAG_FILE); try { command.write(String.valueOf(timeDiffInSecs)); command.write("\n"); command.write(String.valueOf(alarmTimeInMillis / 1000)); command.write("\n"); alarm_duration_setup(mContext, command); alarm_path_setup(getAlarmPath(mContext, alarm), command); // bug[20603] to resolve clock don't alarm on right time 2012.06.20 add begin command.write(snooze_duration); command.write("\n"); // bug[20603] to resolve clock don't alarm on right time 2012.06.20 add end } finally { command.close(); Log.v(ALARM_FLAG_FILE + " write done"); } } catch (Exception e) { Log.v(ALARM_FLAG_FILE + "write error"); } }
private long normalizeTimeOfDayPart(long t, TimeZone tz) { long millis = t; long low = -tz.getOffset(millis); long high = low + DAY; if (millis < low) { do { millis += DAY; } while (millis < low); } else if (millis >= high) { do { millis -= DAY; } while (millis > high); } return millis; }
private String getAsString( FacesContext context, UIInput input, DateTimeConverter converter, Object value) { if (value instanceof Date) { Date dateValue = (Date) value; // Adjust the date to the desired timezone // Dojo expect the the date already formatted within the desired time zone // As the SimpleFormat uses the default timezone, we offset the difference so it is // correctly formatted for dojo. long offset = 0; TimeZone clientTimeZone = converter.getTimeZone(); TimeZone serverTimeZone = TimeZone.getDefault(); if (!serverTimeZone.equals(clientTimeZone)) { // SPR#MKEE9HYGXB cannot use timeZone.getRawOffset() // because client timezone is-summerTime-ness and the // server timezone is-summerTime-ness may be different, // so using the raw offset leads to problems during the // period where one timezone has changed to summer time // but the other timezone has not. Date serverNow = new Date(); Date clientNow = java.util.Calendar.getInstance(clientTimeZone).getTime(); offset = serverTimeZone.getOffset(serverNow.getTime()) - clientTimeZone.getOffset(clientNow.getTime()); } dateValue = new Date(dateValue.getTime() - offset); int type = getValueType(input); return formatValueAsType(dateValue, type); } // TODO should probably not fall through to the non-ISO date converter. if (null == value || "".equals(value)) { return ""; } return value.toString(); }
private void displayTZ(TimeZone... timezone) { System.out.printf( "%32s, %5s \t,%15s\t,%15s,%6s\n", "Time Zone", "inDST", "offset", "DSTSavings", "useDST"); Date date = new Date(); for (TimeZone tz : timezone) { System.out.printf( "%32s, %5s \t,%15d(%d)\t,%15d,%6s\n", tz.getID(), tz.inDaylightTime(date), tz.getOffset(date.getTime()), tz.getOffset(date.getTime()) / (60 * 60 * 1000), tz.getDSTSavings(), tz.useDaylightTime()); } }
private static Object getValue(AtomicValue value, CommandContext context) throws XPathException { if (value instanceof CalendarValue) { CalendarValue cv = (CalendarValue) value; if (!cv.hasTimezone()) { TimeZone tz = context.getServerTimeZone(); int tzMin = tz.getRawOffset() / 60000; if (tz.getDSTSavings() > 0) { tzMin = tz.getOffset(cv.getCalendar().getTimeInMillis()) / 60000; } cv.setTimezoneInMinutes(tzMin); Calendar cal = cv.getCalendar(); return new Timestamp(cal.getTime().getTime()); } } return SequenceTool.convertToJava(value); }
/** * Constructor. * * @param start_time Timestamp of the start time of the graph. * @param end_time Timestamp of the end time of the graph. * @param tz Timezone to use to render the timestamps. If {@code null} the current timezone as of * when the JVM started is used. * @throws IllegalArgumentException if either timestamp is 0 or negative. * @throws IllegalArgumentException if {@code start_time >= end_time}. * @since 1.1 */ public Plot(final long start_time, final long end_time, TimeZone tz) { if ((start_time & 0xFFFFFFFF00000000L) != 0) { throw new IllegalArgumentException("Invalid start time: " + start_time); } else if ((end_time & 0xFFFFFFFF00000000L) != 0) { throw new IllegalArgumentException("Invalid end time: " + end_time); } else if (start_time >= end_time) { throw new IllegalArgumentException( "start time (" + start_time + ") is greater than or equal to end time: " + end_time); } this.start_time = (int) start_time; this.end_time = (int) end_time; if (tz == null) { tz = DEFAULT_TZ; } this.utc_offset = (short) (tz.getOffset(System.currentTimeMillis()) / 1000); }
@Test public void testGetOffset() { TimeZone l_tz = TimeZone.getTimeZone("America/Los_Angeles"); Date today = new Date(); long actual = l_tz.getOffset(today.getTime()); long expected = 0; if (l_tz.getDSTSavings() > 0) { expected = -25200000; } else { expected = -28800000; } // expected = l_tz.get assertEquals(expected, actual); }
public void testParseTimeZoneEndToEnd() { TimeZone tz = CalendarUtilities.tziStringToTimeZone(AMERICA_DAWSON_TIME); assertEquals("America/Dawson", tz.getID()); tz = CalendarUtilities.tziStringToTimeZone(ASIA_CALCUTTA_TIME); assertEquals("Asia/Calcutta", tz.getID()); tz = CalendarUtilities.tziStringToTimeZone(AUSTRALIA_ACT_TIME); assertEquals("Australia/ACT", tz.getID()); tz = CalendarUtilities.tziStringToTimeZone(EUROPE_MOSCOW_TIME); assertEquals("Europe/Moscow", tz.getID()); tz = CalendarUtilities.tziStringToTimeZone(GMT_UNKNOWN_DAYLIGHT_TIME); int bias = tz.getOffset(System.currentTimeMillis()); assertEquals(0, bias); // Make sure non-DST TZ's work properly tz = CalendarUtilities.tziStringToTimeZone(ARIZONA_TIME); assertEquals("America/Phoenix", tz.getID()); }