public Date convertToSystemTimeZone(String datetoconvert) { TimeZone tz = TimeZone.getDefault(); Date date = new Date(); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String s = datetoconvert; String[] tmp = s.split(".0Z"); String s1 = tmp[0]; logger.debug("given string is" + s1); date = dateFormat.parse(s1); logger.debug("OffsetValue is " + tz.getRawOffset()); if (tz.getRawOffset() != 0) date = new Date(date.getTime() + tz.getRawOffset()); logger.debug("After adding offset" + date); if (tz.inDaylightTime(date)) { Date dstDate = new Date(date.getTime() + tz.getDSTSavings()); logger.debug("Day Light Saving is " + tz.getDSTSavings()); logger.debug("Dst is " + dstDate); if (tz.inDaylightTime(dstDate)) { date = dstDate; // logger.debug("dst date "+ dstDate); } } logger.debug("After the day light saving" + date); } catch (Exception e) { logger.debug("System exception caught" + e); } return date; }
@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); }
// @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); }
public static Date localDateToUTC(Date dtLocal) { if (dtLocal == null) return null; TimeZone tz = TimeZone.getDefault(); int currentOffsetFromUTC = tz.getRawOffset() + (tz.inDaylightTime(dtLocal) ? tz.getDSTSavings() : 0); return new Date(dtLocal.getTime() - currentOffsetFromUTC); }
public static void main(final String[] args) { if (args.length >= 2) { final String localeSetting = args[0]; System.out.println("Setting Locale to " + localeSetting + "\n"); Locale.setDefault(new Locale(localeSetting)); final String timezoneSetting = args[1]; System.out.println("Setting TimeZone to " + timezoneSetting + "\n"); TimeZone.setDefault(TimeZone.getTimeZone(timezoneSetting)); } final Locale locale = Locale.getDefault(); System.out.println("Locale"); System.out.println("Code: " + locale.toString()); try { System.out.println("Country: " + locale.getISO3Country()); } catch (final MissingResourceException e) { System.out.println("Country: " + e.getMessage()); } try { System.out.println("Language: " + locale.getISO3Language()); } catch (final MissingResourceException e) { System.out.println("Language: " + e.getMessage()); } System.out.println("\nTimezone"); final TimeZone timezone = TimeZone.getDefault(); System.out.println("Code: " + timezone.getID()); System.out.println("Name: " + timezone.getDisplayName()); System.out.println("Offset: " + timezone.getRawOffset() / (1000 * 60 * 60)); System.out.println("DST: " + timezone.getDSTSavings() / (1000 * 60 * 60)); }
public String toSubtitle() { String result = "UTC" + Utils.offsetString(timeZone.getRawOffset(), true, false); if (timeZone.useDaylightTime()) { result += " / DST " + Utils.offsetString(timeZone.getDSTSavings(), false, true); // String.format(Locale.US, " / DST %+d minutes", timeZone.getDSTSavings()/1000/60); } return result; }
/** * Get the DST offset (if any) for the default locale and the given date. * * @param self a Date * @return the DST offset as a Duration. */ public static Duration getDaylightSavingsOffset(Date self) { TimeZone timeZone = getTimeZone(self); int millis = (timeZone.useDaylightTime() && timeZone.inDaylightTime(self)) ? timeZone.getDSTSavings() : 0; return new TimeDuration(0, 0, 0, millis); }
public void onDateSelect(SelectEvent selectEvent) { Date event = (Date) selectEvent.getObject(); Schedule schedule = (Schedule) selectEvent.getComponent(); final TimeZone timeZone = schedule.calculateTimeZone(); System.out.println( event + ": is in DaylightTime:" + timeZone.inDaylightTime(event) + ", getDSTSavings: " + timeZone.getDSTSavings()); Calendar startDate = new GregorianCalendar(); startDate.setTime(event); if (timeZone.inDaylightTime(event)) { startDate.add(Calendar.MILLISECOND, timeZone.getDSTSavings() * -1); event = startDate.getTime(); } System.out.println("event start: " + event); Date now = new Date(); startDate.setTime(now); startDate.add(Calendar.SECOND, 10); Trigger trigger = newTrigger().withIdentity("eventName", "eventGroup").startAt(startDate.getTime()).build(); JobDetail job = newJob(MailJobJoinedToDeliveryDate.class) .withIdentity("deliverydate.isnull{" + startDate.getTime() + "}", "group-name") .build(); try { scheduler.scheduleJob(job, trigger); } catch (SchedulerException e) { e.printStackTrace(); } Calendar endDate = new GregorianCalendar(); endDate.setTime(startDate.getTime()); endDate.add(Calendar.HOUR, 1); BaseScheduleEvent scevent = new BaseScheduleEvent(); scevent.setStartDate(startDate.getTime()); scevent.setEndDate(endDate.getTime()); scevent.setId("1"); scevent.setTitle("teszt"); eventModel.addEvent(scevent); }
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()); } }
@Override public void format(ByteArrayOutputStream buf) { if (buf == null) { return; } // DTTZ object int tag = 0x80 | CommandType.PROVIDE_LOCAL_INFORMATION.value(); buf.write(tag); // tag byte[] data = new byte[8]; data[0] = 0x07; // Write length of DTTZ data if (mCalendar == null) { mCalendar = Calendar.getInstance(); } // Fill year byte data[1] = byteToBCD(mCalendar.get(java.util.Calendar.YEAR) % 100); // Fill month byte data[2] = byteToBCD(mCalendar.get(java.util.Calendar.MONTH) + 1); // Fill day byte data[3] = byteToBCD(mCalendar.get(java.util.Calendar.DATE)); // Fill hour byte data[4] = byteToBCD(mCalendar.get(java.util.Calendar.HOUR_OF_DAY)); // Fill minute byte data[5] = byteToBCD(mCalendar.get(java.util.Calendar.MINUTE)); // Fill second byte data[6] = byteToBCD(mCalendar.get(java.util.Calendar.SECOND)); String tz = SystemProperties.get("persist.sys.timezone", ""); if (TextUtils.isEmpty(tz)) { data[7] = (byte) 0xFF; // set FF in terminal response } else { TimeZone zone = TimeZone.getTimeZone(tz); int zoneOffset = zone.getRawOffset() + zone.getDSTSavings(); data[7] = getTZOffSetByte(zoneOffset); } for (byte b : data) { buf.write(b); } }
@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); }
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); }
/** * Creates a timestamp from the equivalent long value. This conversion takes account of the time * zone and any daylight savings time. * * @param timestamp timestamp expressed as a long integer * @return new Date instance */ public static Date getTimestampFromLong(long timestamp) { TimeZone tz = TimeZone.getDefault(); Date result = new Date(timestamp - tz.getRawOffset()); if (tz.inDaylightTime(result) == true) { int savings; if (HAS_DST_SAVINGS == true) { savings = tz.getDSTSavings(); } else { savings = DEFAULT_DST_SAVINGS; } result = new Date(result.getTime() - savings); } return (result); }
private Date cvtToGmt(Date date) { TimeZone tz = TimeZone.getDefault(); Date ret = new Date(date.getTime() - tz.getRawOffset()); // if we are now in DST, back off by the delta. Note that we are checking the GMT date, this is // the KEY. if (tz.inDaylightTime(ret)) { Date dstDate = new Date(ret.getTime() - tz.getDSTSavings()); // check to make sure we have not crossed back into standard time // this happens when we are on the cusp of DST (7pm the day before the change for PDT) if (tz.inDaylightTime(dstDate)) { ret = dstDate; } } return ret; }
// @Ignore @Test public void createTimeZoneTest() { String[] availableIds = TimeZone.getAvailableIDs(); TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); Date today = new Date(); for (String id : availableIds) { tz = TimeZone.getTimeZone(id); m_logger.info( "tz info: " + tz.getDisplayName() + "/" + tz.getDSTSavings() + "/" + tz.getOffset(today.getTime())); } assertTrue(true); }
public DateTimeZone getZone(String id) { if (id == null) { return DateTimeZone.UTC; } TimeZone tz = TimeZone.getTimeZone(id); if (tz == null) { return DateTimeZone.UTC; } int rawOffset = tz.getRawOffset(); // sub-optimal. could be improved to only create a new Date every few // minutes if (tz.inDaylightTime(new Date())) { rawOffset += tz.getDSTSavings(); } return DateTimeZone.forOffsetMillis(rawOffset); }
// detect daylight saving in a given date private double detectDaylightSaving() { TimeZone timez = TimeZone.getDefault(); double hoursDiff = timez.getDSTSavings(); return hoursDiff; }
private double detectDaylightSaving(TimeZone timeZone) { double hoursDiff = timeZone.getDSTSavings(); return hoursDiff; }
public static String getTimeZone(String timezone) { TimeZone timeZone = TimeZone.getTimeZone(timezone); int rawOffset = timeZone.getRawOffset(); return String.valueOf(0 - (rawOffset / 60000 + timeZone.getDSTSavings() / 60000)); }
/** * This method parses the specified string into a date. * * @param dateStr The date string to parse. * @param pos The input and output parse position * @return The parsed date, or <code>null</code> if the string cannot be parsed. */ public Date parse(String dateStr, ParsePosition pos) { int fmt_index = 0; int fmt_max = pattern.length(); calendar.clear(); boolean saw_timezone = false; int quote_start = -1; boolean is2DigitYear = false; try { for (; fmt_index < fmt_max; ++fmt_index) { char ch = pattern.charAt(fmt_index); if (ch == '\'') { int index = pos.getIndex(); if (fmt_index < fmt_max - 1 && pattern.charAt(fmt_index + 1) == '\'') { if (!expect(dateStr, pos, ch)) return null; ++fmt_index; } else quote_start = quote_start < 0 ? fmt_index : -1; continue; } if (quote_start != -1 || ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z'))) { if (!expect(dateStr, pos, ch)) return null; continue; } // We've arrived at a potential pattern character in the // pattern. int fmt_count = 1; while (++fmt_index < fmt_max && pattern.charAt(fmt_index) == ch) { ++fmt_count; } // We might need to limit the number of digits to parse in // some cases. We look to the next pattern character to // decide. boolean limit_digits = false; if (fmt_index < fmt_max && standardChars.indexOf(pattern.charAt(fmt_index)) >= 0) limit_digits = true; --fmt_index; // We can handle most fields automatically: most either are // numeric or are looked up in a string vector. In some cases // we need an offset. When numeric, `offset' is added to the // resulting value. When doing a string lookup, offset is the // initial index into the string array. int calendar_field; boolean is_numeric = true; int offset = 0; boolean maybe2DigitYear = false; boolean oneBasedHour = false; boolean oneBasedHourOfDay = false; Integer simpleOffset; String[] set1 = null; String[] set2 = null; switch (ch) { case 'd': calendar_field = Calendar.DATE; break; case 'D': calendar_field = Calendar.DAY_OF_YEAR; break; case 'F': calendar_field = Calendar.DAY_OF_WEEK_IN_MONTH; break; case 'E': is_numeric = false; offset = 1; calendar_field = Calendar.DAY_OF_WEEK; set1 = formatData.getWeekdays(); set2 = formatData.getShortWeekdays(); break; case 'w': calendar_field = Calendar.WEEK_OF_YEAR; break; case 'W': calendar_field = Calendar.WEEK_OF_MONTH; break; case 'M': calendar_field = Calendar.MONTH; if (fmt_count <= 2) offset = -1; else { is_numeric = false; set1 = formatData.getMonths(); set2 = formatData.getShortMonths(); } break; case 'y': calendar_field = Calendar.YEAR; if (fmt_count <= 2) maybe2DigitYear = true; break; case 'K': calendar_field = Calendar.HOUR; break; case 'h': calendar_field = Calendar.HOUR; oneBasedHour = true; break; case 'H': calendar_field = Calendar.HOUR_OF_DAY; break; case 'k': calendar_field = Calendar.HOUR_OF_DAY; oneBasedHourOfDay = true; break; case 'm': calendar_field = Calendar.MINUTE; break; case 's': calendar_field = Calendar.SECOND; break; case 'S': calendar_field = Calendar.MILLISECOND; break; case 'a': is_numeric = false; calendar_field = Calendar.AM_PM; set1 = formatData.getAmPmStrings(); break; case 'z': case 'Z': // We need a special case for the timezone, because it // uses a different data structure than the other cases. is_numeric = false; calendar_field = Calendar.ZONE_OFFSET; String[][] zoneStrings = formatData.getZoneStrings(); int zoneCount = zoneStrings.length; int index = pos.getIndex(); boolean found_zone = false; simpleOffset = computeOffset(dateStr.substring(index)); if (simpleOffset != null) { found_zone = true; saw_timezone = true; calendar.set(Calendar.DST_OFFSET, 0); offset = simpleOffset.intValue(); } else { for (int j = 0; j < zoneCount; j++) { String[] strings = zoneStrings[j]; int k; for (k = 0; k < strings.length; ++k) { if (dateStr.startsWith(strings[k], index)) break; } if (k != strings.length) { found_zone = true; saw_timezone = true; TimeZone tz = TimeZone.getTimeZone(strings[0]); // Check if it's a DST zone or ordinary if (k == 3 || k == 4) calendar.set(Calendar.DST_OFFSET, tz.getDSTSavings()); else calendar.set(Calendar.DST_OFFSET, 0); offset = tz.getRawOffset(); pos.setIndex(index + strings[k].length()); break; } } } if (!found_zone) { pos.setErrorIndex(pos.getIndex()); return null; } break; default: pos.setErrorIndex(pos.getIndex()); return null; } // Compute the value we should assign to the field. int value; int index = -1; if (is_numeric) { numberFormat.setMinimumIntegerDigits(fmt_count); if (limit_digits) numberFormat.setMaximumIntegerDigits(fmt_count); if (maybe2DigitYear) index = pos.getIndex(); Number n = numberFormat.parse(dateStr, pos); if (pos == null || !(n instanceof Long)) return null; value = n.intValue() + offset; } else if (set1 != null) { index = pos.getIndex(); int i; boolean found = false; for (i = offset; i < set1.length; ++i) { if (set1[i] != null) if (dateStr.toUpperCase().startsWith(set1[i].toUpperCase(), index)) { found = true; pos.setIndex(index + set1[i].length()); break; } } if (!found && set2 != null) { for (i = offset; i < set2.length; ++i) { if (set2[i] != null) if (dateStr.toUpperCase().startsWith(set2[i].toUpperCase(), index)) { found = true; pos.setIndex(index + set2[i].length()); break; } } } if (!found) { pos.setErrorIndex(index); return null; } value = i; } else value = offset; if (maybe2DigitYear) { // Parse into default century if the numeric year string has // exactly 2 digits. int digit_count = pos.getIndex() - index; if (digit_count == 2) { is2DigitYear = true; value += defaultCentury; } } // Calendar uses 0-based hours. // I.e. 00:00 AM is midnight, not 12 AM or 24:00 if (oneBasedHour && value == 12) value = 0; if (oneBasedHourOfDay && value == 24) value = 0; // Assign the value and move on. calendar.set(calendar_field, value); } if (is2DigitYear) { // Apply the 80-20 heuristic to dermine the full year based on // defaultCenturyStart. int year = calendar.get(Calendar.YEAR); if (calendar.getTime().compareTo(defaultCenturyStart) < 0) calendar.set(Calendar.YEAR, year + 100); } if (!saw_timezone) { // Use the real rules to determine whether or not this // particular time is in daylight savings. calendar.clear(Calendar.DST_OFFSET); calendar.clear(Calendar.ZONE_OFFSET); } return calendar.getTime(); } catch (IllegalArgumentException x) { pos.setErrorIndex(pos.getIndex()); return null; } }
private int parseTimeZone(String string, int offset) { boolean foundGMT = string.regionMatches(offset, "GMT", 0, 3); if (foundGMT) { offset += 3; } char sign; if (offset < string.length() && ((sign = string.charAt(offset)) == '+' || sign == '-')) { ParsePosition position = new ParsePosition(offset + 1); Number result = numberFormat.parse(string, position); if (result == null) { return -position.getErrorIndex() - 1; } int hour = result.intValue(); int raw = hour * 3600000; int index = position.getIndex(); if (index < string.length() && string.charAt(index) == ':') { position.setIndex(index + 1); result = numberFormat.parse(string, position); if (result == null) { return -position.getErrorIndex() - 1; } int minute = result.intValue(); raw += minute * 60000; } else if (hour >= 24) { raw = (hour / 100 * 3600000) + (hour % 100 * 60000); } if (sign == '-') { raw = -raw; } calendar.setTimeZone(new SimpleTimeZone(raw, "")); return position.getIndex(); } if (foundGMT) { calendar.setTimeZone(TimeZone.getTimeZone("GMT")); return offset; } for (String[] row : formatData.internalZoneStrings()) { for (int i = TimeZoneNames.LONG_NAME; i < TimeZoneNames.NAME_COUNT; ++i) { if (row[i] == null) { // If icu4c doesn't have a name, our array contains a null. Normally we'd // work out the correct GMT offset, but we already handled parsing GMT offsets continue; } if (string.regionMatches(true, offset, row[i], 0, row[i].length())) { TimeZone zone = TimeZone.getTimeZone(row[TimeZoneNames.OLSON_NAME]); if (zone == null) { return -offset - 1; } int raw = zone.getRawOffset(); if (i == TimeZoneNames.LONG_NAME_DST || i == TimeZoneNames.SHORT_NAME_DST) { // Not all time zones use a one-hour difference, so we need to query // the TimeZone. (Australia/Lord_Howe is the usual example of this.) int dstSavings = zone.getDSTSavings(); // One problem with TimeZone.getDSTSavings is that it will return 0 if the // time zone has stopped using DST, even if we're parsing a date from // the past. In that case, assume the default. if (dstSavings == 0) { // TODO: we should change this to use TimeZone.getOffset(long), // but that requires the complete date to be parsed first. dstSavings = 3600000; } raw += dstSavings; } calendar.setTimeZone(new SimpleTimeZone(raw, "")); return offset + row[i].length(); } } } return -offset - 1; }
/** * Get the client's time zone if that could be detected. * * @return The client's time zone */ public TimeZone getTimeZone() { if (timeZone == null) { String utc = getUtcOffset(); if (utc != null) { // apparently it is platform dependent on whether you get the // offset in a decimal form or not. This parses the decimal // form of the UTC offset, taking into account several // possibilities // such as getting the format in +2.5 or -1.2 int dotPos = utc.indexOf('.'); if (dotPos >= 0) { String hours = utc.substring(0, dotPos); String hourPart = utc.substring(dotPos + 1); if (hours.startsWith("+")) { hours = hours.substring(1); } int offsetHours = Integer.parseInt(hours); int offsetMins = (int) (Double.parseDouble(hourPart) * 6); // construct a GMT timezone offset string from the retrieved // offset which can be parsed by the TimeZone class. AppendingStringBuffer sb = new AppendingStringBuffer("GMT"); sb.append(offsetHours > 0 ? "+" : "-"); sb.append(Math.abs(offsetHours)); sb.append(":"); if (offsetMins < 10) { sb.append("0"); } sb.append(offsetMins); timeZone = TimeZone.getTimeZone(sb.toString()); } else { int offset = Integer.parseInt(utc); if (offset < 0) { utc = utc.substring(1); } timeZone = TimeZone.getTimeZone("GMT" + ((offset > 0) ? "+" : "-") + utc); } String dstOffset = getUtcDSTOffset(); if (timeZone != null && dstOffset != null) { TimeZone dstTimeZone = null; dotPos = dstOffset.indexOf('.'); if (dotPos >= 0) { String hours = dstOffset.substring(0, dotPos); String hourPart = dstOffset.substring(dotPos + 1); if (hours.startsWith("+")) { hours = hours.substring(1); } int offsetHours = Integer.parseInt(hours); int offsetMins = (int) (Double.parseDouble(hourPart) * 6); // construct a GMT timezone offset string from the // retrieved // offset which can be parsed by the TimeZone class. AppendingStringBuffer sb = new AppendingStringBuffer("GMT"); sb.append(offsetHours > 0 ? "+" : "-"); sb.append(Math.abs(offsetHours)); sb.append(":"); if (offsetMins < 10) { sb.append("0"); } sb.append(offsetMins); dstTimeZone = TimeZone.getTimeZone(sb.toString()); } else { int offset = Integer.parseInt(dstOffset); if (offset < 0) { dstOffset = dstOffset.substring(1); } dstTimeZone = TimeZone.getTimeZone("GMT" + ((offset > 0) ? "+" : "-") + dstOffset); } // if the dstTimezone (1 July) has a different offset then // the real time zone (1 January) try to combine the 2. if (dstTimeZone != null && dstTimeZone.getRawOffset() != timeZone.getRawOffset()) { int dstSaving = dstTimeZone.getRawOffset() - timeZone.getRawOffset(); String[] availableIDs = TimeZone.getAvailableIDs(timeZone.getRawOffset()); for (String availableID : availableIDs) { TimeZone zone = TimeZone.getTimeZone(availableID); if (zone.getDSTSavings() == dstSaving) { // this is a best guess... still the start and end of the DST should // be needed to know to be completely correct, or better yet // not just the GMT offset but the TimeZone ID should be transfered // from the browser. timeZone = zone; break; } } } } } } return timeZone; }