public override DaylightTime GetDaylightChanges(int year) { if ((year < 1) || (year > 0x270f)) { throw new ArgumentOutOfRangeException("year", string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), new object[] { 1, 0x270f })); } object key = year; if (!this.m_CachedDaylightChanges.Contains(key)) { lock (InternalSyncObject) { if (!this.m_CachedDaylightChanges.Contains(key)) { short[] numArray = nativeGetDaylightChanges(); if (numArray == null) { this.m_CachedDaylightChanges.Add(key, new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero)); } else { DateTime start = GetDayOfWeek(year, numArray[0] != 0, numArray[1], numArray[2], numArray[3], numArray[4], numArray[5], numArray[6], numArray[7]); DateTime end = GetDayOfWeek(year, numArray[8] != 0, numArray[9], numArray[10], numArray[11], numArray[12], numArray[13], numArray[14], numArray[15]); TimeSpan delta = new TimeSpan(numArray[0x10] * 0x23c34600L); DaylightTime time3 = new DaylightTime(start, end, delta); this.m_CachedDaylightChanges.Add(key, time3); } } } } return (DaylightTime) this.m_CachedDaylightChanges[key]; }
/** * Randomized testing of dst status. */ public void TestIsDST(int tz, DaylightTime dst) { DateTime lower = dst.Start; DateTime upper = dst.End; DateTime year_lower = new DateTime(lower.Year, 1, 1, 0, 0, 0); DateTime year_upper = new DateTime(upper.Year, 12, 31, 23, 59, 59); DateTime dt_pre = Rand.GetDateTime(year_lower, lower); DateTime dt_in = Rand.GetDateTime(lower, upper); DateTime dt_post = Rand.GetDateTime(upper, year_upper); UTCDate dst_pre = new UTCDate(tz, dst, dt_pre.Year, dt_pre.Month, dt_pre.Day, dt_pre.Hour, dt_pre.Minute, dt_pre.Second); UTCDate dst_in = new UTCDate(tz, dst, dt_in.Year, dt_in.Month, dt_in.Day, dt_in.Hour, dt_in.Minute, dt_in.Second); UTCDate dst_post = new UTCDate(tz, dst, dt_post.Year, dt_post.Month, dt_post.Day, dt_post.Hour, dt_post.Minute, dt_post.Second); Assert.IsFalse(dst_pre.IsDST); Assert.IsTrue(dst_in.IsDST); Assert.IsFalse(dst_post.IsDST); }
void TimeZoneInfoExamples() { TimeZoneInfo localInfo = TimeZoneInfo.Local; Console.WriteLine(localInfo); Console.WriteLine(localInfo.StandardName); TimeZoneInfo aus = TimeZoneInfo.FindSystemTimeZoneById("W. Australia Standard Time"); Console.WriteLine(aus); Console.WriteLine(aus.SupportsDaylightSavingTime); Console.WriteLine(aus.IsDaylightSavingTime(DateTime.Now)); aus.IsAmbiguousTime(DateTime.Now); // true if a time which was repeated for daylight savings aus.IsInvalidTime(DateTime.Now); // true if the time was skipped due to day light sayings // aus.GetAmbiguousTimeOffsets(DateTime.Now); throws exception if not ambiguous // Comparisions that rely on timemoving forward will break if they use local datetime Console.WriteLine(DateTime.Now.IsDaylightSavingTime()); System.Globalization.DaylightTime time = TimeZone.CurrentTimeZone.GetDaylightChanges(2017); Console.WriteLine(time.Start); Console.WriteLine(time.End); Console.WriteLine(time.Delta); DateTime forComparing = DateTime.UtcNow; Console.WriteLine(forComparing.ToLocalTime()); }
static int IsDaylightSavingTime(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 2 && TypeChecker.CheckTypes <System.DateTime, System.Globalization.DaylightTime>(L, 1)) { System.DateTime arg0 = StackTraits <System.DateTime> .To(L, 1); System.Globalization.DaylightTime arg1 = (System.Globalization.DaylightTime)ToLua.ToObject(L, 2); bool o = System.TimeZone.IsDaylightSavingTime(arg0, arg1); LuaDLL.lua_pushboolean(L, o); return(1); } else if (count == 2 && TypeChecker.CheckTypes <System.TimeZone, System.DateTime>(L, 1)) { System.TimeZone obj = (System.TimeZone)ToLua.ToObject(L, 1); System.DateTime arg0 = StackTraits <System.DateTime> .To(L, 2); bool o = obj.IsDaylightSavingTime(arg0); LuaDLL.lua_pushboolean(L, o); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: System.TimeZone.IsDaylightSavingTime")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
// Determine if a specified time is within the daylight savings period. public static bool IsDaylightSavingTime (DateTime time, DaylightTime daylightTimes) { // If there are no daylight savings rules, then bail out. if(daylightTimes == null) { return false; } // The period needs to be calculated differently depending // upon whether the delta is positive or negative. DateTime start, end; if(daylightTimes.Delta.Ticks > 0) { start = daylightTimes.Start + daylightTimes.Delta; end = daylightTimes.End; } else { start = daylightTimes.Start; end = daylightTimes.End - daylightTimes.Delta; } // Detect which hemisphere the information is for. if(start > end) { // Southern hemisphere with summer at year's end. return (time < start || time >= end); } else { // Northern hemisphere with summer in mid-year. return (time >= start && time < end); } }
public void Constructor () { DaylightTime dt = new DaylightTime (DateTime.MinValue, DateTime.MaxValue, TimeSpan.MinValue); Assert.AreEqual (DateTime.MinValue, dt.Start, "Start"); Assert.AreEqual (DateTime.MaxValue, dt.End, "End"); Assert.AreEqual (TimeSpan.MinValue, dt.Delta, "Delta"); }
// ########################################################## // ### Constructors // ########################################################## /** * Create an instance resetting the time to UTC */ public UTCDate(double tz, DaylightTime dst, int year, int month, int day, int hour, int min, int sec) { this.tz = tz; this.dst = dst; DateTime dt = new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc); dt = ResolveTimezone(dt, tz); this.dt = ResolveDST(dt, dst); CheckTimezone(this.tz); }
public void SerializationRoundtrip () { DaylightTime dt = new DaylightTime (DateTime.MinValue, DateTime.MaxValue, TimeSpan.MinValue); BinaryFormatter bf = new BinaryFormatter (); MemoryStream ms = new MemoryStream (); bf.Serialize (ms, dt); ms.Position = 0; DaylightTime clone = (DaylightTime) bf.Deserialize (ms); Assert.AreEqual (clone.Start, dt.Start, "Start"); Assert.AreEqual (clone.End, dt.End, "End"); Assert.AreEqual (clone.Delta, dt.Delta, "Delta"); }
static int GetDaylightChanges(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); System.TimeZone obj = (System.TimeZone)ToLua.CheckObject <System.TimeZone>(L, 1); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); System.Globalization.DaylightTime o = obj.GetDaylightChanges(arg0); ToLua.PushObject(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes) { if (daylightTimes != null) { DateTime time4; DateTime time5; if (time.Kind == DateTimeKind.Utc) { return TimeSpan.Zero; } DateTime time2 = daylightTimes.Start + daylightTimes.Delta; DateTime end = daylightTimes.End; if (daylightTimes.Delta.Ticks > 0L) { time4 = end - daylightTimes.Delta; time5 = end; } else { time4 = time2; time5 = time2 - daylightTimes.Delta; } bool flag = false; if (time2 > end) { if ((time >= time2) || (time < end)) { flag = true; } } else if ((time >= time2) && (time < end)) { flag = true; } if ((flag && (time >= time4)) && (time < time5)) { flag = time.IsAmbiguousDaylightSavingTime(); } if (flag) { return daylightTimes.Delta; } } return TimeSpan.Zero; }
/// <summary> /// Returns a value indicating whether the specified date and time is within /// the specified daylight saving time period. /// </summary> /// <param name="time">A date and time.</param> /// <param name="daylightTimes">A daylight saving time period.</param> /// <returns> /// true if time is in daylightTimes; otherwise, false. /// </returns> public static new bool IsDaylightSavingTime(DateTime time, DaylightTime daylightTimes) { return TimeZone.IsDaylightSavingTime(time, daylightTimes); }
// Check if the specified time is in a daylight saving time. Allows the user to // specify the array of Daylight Saving Times. public static bool IsDaylightSavingTime(DateTime time, DaylightTime daylightTimes) { return CalculateUtcOffset(time, daylightTimes)!=TimeSpan.Zero; }
private void OnDeserialization (DaylightTime dlt) { if (dlt == null) { Int64[] data; string[] names; this_year = DateTime.Now.Year; if (!GetTimeZoneData (this_year, out data, out names)) throw new ArgumentException (Locale.GetText ("Can't get timezone data for " + this_year)); dlt = GetDaylightTimeFromData (data); } else this_year = dlt.Start.Year; utcOffsetWithOutDLS = new TimeSpan (m_ticksOffset); utcOffsetWithDLS = new TimeSpan (m_ticksOffset + dlt.Delta.Ticks); this_year_dlt = dlt; }
public override DaylightTime GetDaylightChanges(int year) { if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 9999)); } Contract.EndContractBlock(); Object objYear = (Object) year; if (!m_CachedDaylightChanges.Contains(objYear)) { DaylightTime currentDaylightChanges = null; if (TimeZoneInfo.Local.SupportsDaylightSavingTime) { DateTime start; DateTime end; TimeSpan delta; foreach (var rule in TimeZoneInfo.Local.GetAdjustmentRules()) { if (rule.DateStart.Year <= year && rule.DateEnd.Year >= year && rule.DaylightDelta != TimeSpan.Zero) { start = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionStart); end = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionEnd); delta = rule.DaylightDelta; currentDaylightChanges = new DaylightTime(start, end, delta); break; } } } if (currentDaylightChanges == null) { currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero); } lock (m_CachedDaylightChanges) { if (!m_CachedDaylightChanges.Contains(objYear)) { m_CachedDaylightChanges.Add(objYear, currentDaylightChanges); } } } DaylightTime result = (DaylightTime)m_CachedDaylightChanges[objYear]; return result; }
[System.Security.SecuritySafeCritical] // auto-generated public override DaylightTime GetDaylightChanges(int year) { if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 9999)); } Contract.EndContractBlock(); Object objYear = (Object)year; if (!m_CachedDaylightChanges.Contains(objYear)) { lock (InternalSyncObject) { if (!m_CachedDaylightChanges.Contains(objYear)) { // // rawData is an array of 17 short (16 bit) numbers. // The first 8 numbers contains the // year/month/day/dayOfWeek/hour/minute/second/millisecond for the starting time of daylight saving time. // The next 8 numbers contains the // year/month/day/dayOfWeek/hour/minute/second/millisecond for the ending time of daylight saving time. // The last short number is the delta to the standard offset in minutes. // short[] rawData = nativeGetDaylightChanges(year); if (rawData == null) { // // If rawData is null, it means that daylight saving time is not used // in this timezone. So keep currentDaylightChanges as the empty array. // m_CachedDaylightChanges.Add(objYear, new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero)); } else { DateTime start; DateTime end; TimeSpan delta; // // Store the start of daylight saving time. // start = GetDayOfWeek(year, (rawData[0] != 0), rawData[1], rawData[2], rawData[3], rawData[4], rawData[5], rawData[6], rawData[7]); // // Store the end of daylight saving time. // end = GetDayOfWeek(year, (rawData[8] != 0), rawData[9], rawData[10], rawData[11], rawData[12], rawData[13], rawData[14], rawData[15]); delta = new TimeSpan(rawData[16] * TicksPerMinute); DaylightTime currentDaylightChanges = new DaylightTime(start, end, delta); m_CachedDaylightChanges.Add(objYear, currentDaylightChanges); } } } } DaylightTime result = (DaylightTime)m_CachedDaylightChanges[objYear]; return result; }
public static bool IsDaylightSavingTime (DateTime time, DaylightTime daylightTimes) { if (daylightTimes == null) throw new ArgumentNullException ("daylightTimes"); // If Start == End, then DST is off if (daylightTimes.Start.Ticks == daylightTimes.End.Ticks) return false; //We are in the northern hemisphere. if (daylightTimes.Start.Ticks < daylightTimes.End.Ticks) { if (daylightTimes.Start.Ticks < time.Ticks && daylightTimes.End.Ticks > time.Ticks) return true; // time lies between Start and End } else { // We are in the southern hemisphere. if (time.Year == daylightTimes.Start.Year && time.Year == daylightTimes.End.Year) if (time.Ticks < daylightTimes.End.Ticks || time.Ticks > daylightTimes.Start.Ticks) return true; // time is less than End OR more than Start } return false; }
private void GetDaylightChangeRules(ref DateTime time, TzDatabase.TzZone targetZone, DateTimeKind inflectionKind, out TzDatabase.TzRule one, out TzDatabase.TzRule two, out DaylightTime daylightTime) { one = two = null; daylightTime = null; // First, figure out which zone we're in if (targetZone != null) { // The zone might not have any daylight savings time rules if (targetZone.RuleName != TzDatabase.NotApplicableValue) { int index = FindRuleIndex(targetZone, time); if (index != -1) { one = m_info.Rules[index]; two = GetCompanionRule(targetZone, one, index, time); if (one != null && two != null) { DateTime from = one.GetDateTime(time.Year, targetZone.UtcOffset, two); DateTime to = two.GetDateTime(time.Year, targetZone.UtcOffset, one); if (from > to && Info.IsLatitudeNorth) { DateTime swap = to; to = from; from = swap; TzDatabase.TzRule swapRule = one; one = two; two = swapRule; } else if (from < to && !Info.IsLatitudeNorth) { DateTime swap = to; to = from; from = swap; TzDatabase.TzRule swapRule = one; one = two; two = swapRule; } TimeSpan delta = one.SaveTime; if (delta.Ticks == 0) { delta = two.SaveTime; } daylightTime = new DaylightTime(from, to, delta); } } } } }
/// <summary> /// Create a new SunTime object with default settings. /// </summary> public SunTime() { this.latitude = 0.0; this.longitude = 0.0; this.utcOffset = 1.0; this.date = DateTime.Now; this.daylightChanges = TimeZone.CurrentTimeZone.GetDaylightChanges(date.Year); Update(); }
private void AdjustFileForSpringDst(AgdFile agdFile, IDbConnection db, DaylightTime daylightTime) { //see if there's any epochs before DST int epochsBeforeSpringDst = db.Scalar<int>( db.From<AgdTableTimestampAxis1>() .Select(Sql.Count("*")) .Where(q => q.TimestampTicks < daylightTime.Start.Ticks)); bool dataBeforeSpringDst = epochsBeforeSpringDst > 0; int epochsAfterSpringDst = db.Scalar<int>( db.From<AgdTableTimestampAxis1>() .Select(Sql.Count("*")) .Where(q => q.TimestampTicks > daylightTime.Start.Ticks)); bool dataAfterSpringDst = epochsAfterSpringDst > 0; if (!dataBeforeSpringDst && dataAfterSpringDst) { //no need to do anything richTextBox1.AppendText(string.Format("{0}: NOT adjusting file for spring DST\r\n", agdFile)); return; } richTextBox1.AppendText(string.Format("{0}: adjusting file for spring DST\r\n", agdFile)); //adjust timestamps for data after DST by subtracting an hour string sql = string.Format( "UPDATE data SET dataTimestamp = dataTimestamp + {0} WHERE dataTimestamp >= {1}", daylightTime.Delta.Ticks, daylightTime.Start.Ticks); db.ExecuteSql(sql); //add the extra hour of data (October 25th 0200) var totalEpochsToInsert = daylightTime.Delta.TotalSeconds / agdFile.EpochLengthInSeconds; var ticksPerEpoch = TimeSpan.FromSeconds(agdFile.EpochLengthInSeconds).Ticks; for (int i = 0; i < totalEpochsToInsert; i++) { sql = string.Format("insert into data(dataTimestamp) values ({0});", (daylightTime.Start.Ticks + (i * ticksPerEpoch))); db.ExecuteSql(sql); } var columnNames = db.GetColumnNames("data"); foreach (var columnName in columnNames) { sql = string.Format("UPDATE data SET {0} = 0 WHERE {0} IS NULL", columnName); db.ExecuteSql(sql); } //adjust WTV if (db.TableExists("filters")) { sql = string.Format( "UPDATE filters SET filterStartTimestamp = filterStartTimestamp + {0} WHERE filterStartTimestamp >= {1}", daylightTime.Delta.Ticks, daylightTime.Start.Ticks); db.ExecuteSql(sql); sql = string.Format( "UPDATE filters SET filterStopTimestamp = filterStopTimestamp + {0} WHERE filterStopTimestamp >= {1}", daylightTime.Delta.Ticks, daylightTime.Start.Ticks); db.ExecuteSql(sql); } if (db.TableExists("wtvBouts")) { sql = string.Format( "UPDATE wtvBouts SET startTicks = startTicks + {0} WHERE startTicks >= {1}", daylightTime.Delta.Ticks, daylightTime.Start.Ticks); db.ExecuteSql(sql); sql = string.Format( "UPDATE wtvBouts SET stopTicks = stopTicks + {0} WHERE stopTicks >= {1}", daylightTime.Delta.Ticks, daylightTime.Start.Ticks); db.ExecuteSql(sql); } //adjust capsense if (db.TableExists("capsense")) { //adjust timestamps for data after DST by subtracting an hour sql = string.Format( "UPDATE capsense SET timeStamp = timeStamp + {0} WHERE timeStamp >= {1}", daylightTime.Delta.Ticks, daylightTime.Start.Ticks); db.ExecuteSql(sql); } }
private void AdjustFileForFallDst(AgdFile agdFile, IDbConnection db, DaylightTime daylightTime) { //see if there's any epochs before DST int epochsBeforeFallDst = db.Scalar<int>( db.From<AgdTableTimestampAxis1>() .Select(Sql.Count("*")) .Where(q => q.TimestampTicks < daylightTime.End.Ticks)); bool dataBeforeFallDst = epochsBeforeFallDst > 0; int epochsAfterFallDst = db.Scalar<int>( db.From<AgdTableTimestampAxis1>() .Select(Sql.Count("*")) .Where(q => q.TimestampTicks > daylightTime.End.Ticks)); bool dataAfterFallDst = epochsAfterFallDst > 0; if (dataBeforeFallDst && !dataAfterFallDst) { //there's only data before //no need to do anything richTextBox1.AppendText(string.Format("{0}: not adjusting file for fall DST\r\n", agdFile)); return; } richTextBox1.AppendText(string.Format("{0}: adjusting file for fall DST\r\n", agdFile)); //delete the extra hour of data (October 25th 0200) string sql = string.Format("DELETE FROM data WHERE dataTimestamp >= {0} AND dataTimeStamp < {1}", daylightTime.End.Ticks, daylightTime.End.Add(daylightTime.Delta).Ticks); db.ExecuteSql(sql); //adjust timestamps for data after DST by subtracting an hour sql = string.Format( "UPDATE data SET dataTimestamp = dataTimestamp - {0} WHERE dataTimestamp >= {1}", daylightTime.Delta.Ticks, daylightTime.End.Ticks); db.ExecuteSql(sql); //adjust WTV if (db.TableExists("filters")) { sql = string.Format( "UPDATE filters SET filterStartTimestamp = filterStartTimestamp - {0} WHERE filterStartTimestamp >= {1}", daylightTime.Delta.Ticks, daylightTime.End.Ticks); db.ExecuteSql(sql); sql = string.Format( "UPDATE filters SET filterStopTimestamp = filterStopTimestamp - {0} WHERE filterStopTimestamp >= {1}", daylightTime.Delta.Ticks, daylightTime.End.Ticks); db.ExecuteSql(sql); } if (db.TableExists("wtvBouts")) { sql = string.Format( "UPDATE wtvBouts SET startTicks = startTicks - {0} WHERE startTicks >= {1}", daylightTime.Delta.Ticks, daylightTime.End.Ticks); db.ExecuteSql(sql); sql = string.Format( "UPDATE wtvBouts SET stopTicks = stopTicks - {0} WHERE stopTicks >= {1}", daylightTime.Delta.Ticks, daylightTime.End.Ticks); db.ExecuteSql(sql); } //adjust capsense if (db.TableExists("capsense")) { //delete the extra hour of data (October 25th 0200) sql = string.Format("DELETE FROM capsense WHERE timeStamp >= {0} AND timeStamp < {1}", daylightTime.End.Ticks, daylightTime.End.Add(daylightTime.Delta).Ticks); db.ExecuteSql(sql); //adjust timestamps for data after DST by subtracting an hour sql = string.Format( "UPDATE capsense SET timeStamp = timeStamp - {0} WHERE timeStamp >= {1}", daylightTime.Delta.Ticks, daylightTime.End.Ticks); db.ExecuteSql(sql); } }
/** * Obtain absolute date (utc) from relative (local). */ public static DateTime ResolveDST(DateTime dt, DaylightTime dst) { if (IsWithinDST(dt, dst)) { dt = dt.Add(-dst.Delta); } return dt; }
// Get the daylight saving time rules for this timezone in a given year. public override DaylightTime GetDaylightChanges(int year) { long start, end, delta; if(year < 1 || year > 9999) { throw new ArgumentOutOfRangeException (_("ArgRange_Year")); } lock(this) { if(cachedYear == year) { return cachedChanges; } if(TimeMethods.GetDaylightRules (year, out start, out end, out delta)) { cachedChanges = new DaylightTime (new DateTime(start), new DateTime(end), new TimeSpan(delta)); } else { cachedChanges = new DaylightTime (DateTime.MinValue, DateTime.MaxValue, TimeSpan.Zero); } cachedYear = year; return cachedChanges; } }
public FormAnnotation() { InitializeComponent(); //datagridview settings InitializeDataGridView(dataGridView1); button_remove.Image = Resources.Im_delete; button_add.Image = Resources.Im_plus; button_category_select.Image = Resources.Im_next; button_save.Image = Resources.Im_save; button_generate.Image = Resources.Im_gear; button_exit.Image = Resources.Im_stop; //Initialize Time and Time Zone localZone = TimeZone.CurrentTimeZone; daylight = localZone.GetDaylightChanges(DateTime.Now.Year); }
// // NOTENOTE: Implementation detail // In the transition from standard time to daylight saving time, // if we convert local time to Universal time, we can have the // following (take PST as an example): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 09:00 -8:00 // 02:00 (=> 03:00) 10:00 -8:00 [This time doesn't actually exist, but it can be created from DateTime] // 03:00 10:00 -7:00 // 04:00 11:00 -7:00 // 05:00 12:00 -7:00 // // So from 02:00 - 02:59:59, we should return the standard offset, instead of the daylight saving offset. // // In the transition from daylight saving time to standard time, // if we convert local time to Universal time, we can have the // following (take PST as an example): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 08:00 -7:00 // 02:00 (=> 01:00) 09:00 -8:00 // 02:00 10:00 -8:00 // 03:00 11:00 -8:00 // 04:00 12:00 -8:00 // // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this. // But note that there are two 01:00 in the local time. // // And imagine if the daylight saving offset is negative (although this does not exist in real life) // In the transition from standard time to daylight saving time, // if we convert local time to Universal time, we can have the // following (take PST as an example, but the daylight saving offset is -01:00): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 09:00 -8:00 // 02:00 (=> 01:00) 10:00 -9:00 // 02:00 11:00 -9:00 // 03:00 12:00 -9:00 // 04:00 13:00 -9:00 // 05:00 14:00 -9:00 // // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this. // // In the transition from daylight saving time to standard time, // if we convert local time to Universal time, we can have the // following (take PST as an example, daylight saving offset is -01:00): // // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 10:00 -9:00 // 02:00 (=> 03:00) 11:00 -9:00 // 03:00 11:00 -8:00 // 04:00 12:00 -8:00 // 05:00 13:00 -8:00 // 06:00 14:00 -8:00 // // So from 02:00 - 02:59:59, we should return the daylight saving offset, instead of the standard offset. // internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes) { if (daylightTimes==null) { return TimeSpan.Zero; } DateTimeKind kind = time.Kind; if (kind == DateTimeKind.Utc) { return TimeSpan.Zero; } DateTime startTime; DateTime endTime; // startTime and endTime represent the period from either the start of DST to the end and includes the // potentially overlapped times startTime = daylightTimes.Start + daylightTimes.Delta; endTime = daylightTimes.End; // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the // clock back. It is theoretically possible to have a positive delta, (which would really be daylight // reduction time), where you would have to wind the clock back in the begnning. DateTime ambiguousStart; DateTime ambiguousEnd; if (daylightTimes.Delta.Ticks > 0) { ambiguousStart = endTime - daylightTimes.Delta; ambiguousEnd = endTime; } else { ambiguousStart = startTime; ambiguousEnd = startTime - daylightTimes.Delta; } Boolean isDst = false; if (startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. // Note, the summer in the southern hemisphere begins late in the year. if (time >= startTime || time < endTime) { isDst = true; } } else if (time>=startTime && time < endTime) { // In northern hemisphere, the daylight saving time starts in the middle of the year. isDst = true; } // If this date was previously converted from a UTC date and we were able to detect that the local // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity. if (isDst && time >= ambiguousStart && time < ambiguousEnd) { isDst = time.IsAmbiguousDaylightSavingTime(); } if (isDst) { return daylightTimes.Delta; } return TimeSpan.Zero; }
public override DaylightTime GetDaylightChanges(int year) { if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Range", new object[] { 1, 9999 })); } object key = year; if (!this.m_CachedDaylightChanges.Contains(key)) { lock (CurrentSystemTimeZone.InternalSyncObject) { if (!this.m_CachedDaylightChanges.Contains(key)) { short[] array = CurrentSystemTimeZone.nativeGetDaylightChanges(year); if (array == null) { this.m_CachedDaylightChanges.Add(key, new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero)); } else { DateTime dayOfWeek = CurrentSystemTimeZone.GetDayOfWeek(year, array[0] != 0, (int)array[1], (int)array[2], (int)array[3], (int)array[4], (int)array[5], (int)array[6], (int)array[7]); DateTime dayOfWeek2 = CurrentSystemTimeZone.GetDayOfWeek(year, array[8] != 0, (int)array[9], (int)array[10], (int)array[11], (int)array[12], (int)array[13], (int)array[14], (int)array[15]); TimeSpan delta = new TimeSpan((long)array[16] * 600000000L); DaylightTime value = new DaylightTime(dayOfWeek, dayOfWeek2, delta); this.m_CachedDaylightChanges.Add(key, value); } } } } return (DaylightTime)this.m_CachedDaylightChanges[key]; }
public override DaylightTime GetDaylightChanges(int year) { //Check cache... //This was broken. DaylightTime retVal = daylightChanges[this.zoneIndex + ":" + year] as DaylightTime; if (retVal == null) { lock(daylightChangesLock) { DateTime current; DateTime start = DateTime.MinValue; DateTime end = DateTime.MinValue; TimeSpan delta = TimeSpan.FromTicks(0); if ( winTZI.daylightDate.month != 0 && winTZI.standardDate.month != 0 ) { // day count is a value from 1 to 5, indicating the day // in the month on which the switch occurs int dayCount = winTZI.daylightDate.day; current = start = new DateTime( year, winTZI.daylightDate.month, 1, winTZI.daylightDate.hour,winTZI.daylightDate.minute,winTZI.daylightDate.second ); while ( current.Month == winTZI.daylightDate.month ) { if ( Convert.ToUInt16(current.DayOfWeek) == winTZI.daylightDate.dayOfWeek ) { start = current; --dayCount; if ( dayCount == 0 ) { break; } } current = current.AddDays(1); } // day count is a value from 1 to 5, indicating the day // in the month on which the switch occurs dayCount = winTZI.standardDate.day; current = end = new DateTime( year, winTZI.standardDate.month, 1, winTZI.standardDate.hour,winTZI.standardDate.minute,winTZI.standardDate.second ); while ( current.Month == winTZI.standardDate.month ) { if ( Convert.ToUInt16(current.DayOfWeek) == winTZI.standardDate.dayOfWeek ) { end = current; --dayCount; if ( dayCount == 0 ) { break; } } current = current.AddDays(1); } delta = daylightBias - standardBias; } retVal = new DaylightTime(start,end,delta); if (daylightChanges.ContainsKey(this.zoneIndex + ":" + year) == false) { daylightChanges.Add(this.zoneIndex + ":" + year, retVal); } } } return retVal; }
internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes) { if (daylightTimes == null) { return TimeSpan.Zero; } DateTimeKind kind = time.Kind; if (kind == DateTimeKind.Utc) { return TimeSpan.Zero; } DateTime dateTime = daylightTimes.Start + daylightTimes.Delta; DateTime end = daylightTimes.End; DateTime t; DateTime t2; if (daylightTimes.Delta.Ticks > 0L) { t = end - daylightTimes.Delta; t2 = end; } else { t = dateTime; t2 = dateTime - daylightTimes.Delta; } bool flag = false; if (dateTime > end) { if (time >= dateTime || time < end) { flag = true; } } else { if (time >= dateTime && time < end) { flag = true; } } if (flag && time >= t && time < t2) { flag = time.IsAmbiguousDaylightSavingTime(); } if (flag) { return daylightTimes.Delta; } return TimeSpan.Zero; }
// ########################################################## // ### Common public API static methods // ########################################################## public static bool IsWithinDST(DateTime dt, DaylightTime dst) { bool v = false; if (IsNonZero(dst)) { if ((dst.Start < dt) && (dt < dst.End)) { v = true; } } return v; }
// // NOTENOTE: Implementation detail // In the transition from standard time to daylight saving time, // if we convert local time to Universal time, we can have the // following (take PST as an example): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 09:00 -8:00 // 02:00 (=> 03:00) 10:00 -8:00 [This time doesn't actually exist, but it can be created from DateTime] // 03:00 10:00 -7:00 // 04:00 11:00 -7:00 // 05:00 12:00 -7:00 // // So from 02:00 - 02:59:59, we should return the standard offset, instead of the daylight saving offset. // // In the transition from daylight saving time to standard time, // if we convert local time to Universal time, we can have the // following (take PST as an example): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 08:00 -7:00 // 02:00 (=> 01:00) 09:00 -8:00 // 02:00 10:00 -8:00 // 03:00 11:00 -8:00 // 04:00 12:00 -8:00 // // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this. // But note that there are two 01:00 in the local time. // // And imagine if the daylight saving offset is negative (although this does not exist in real life) // In the transition from standard time to daylight saving time, // if we convert local time to Universal time, we can have the // following (take PST as an example, but the daylight saving offset is -01:00): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 09:00 -8:00 // 02:00 (=> 01:00) 10:00 -9:00 // 02:00 11:00 -9:00 // 03:00 12:00 -9:00 // 04:00 13:00 -9:00 // 05:00 14:00 -9:00 // // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this. // // In the transition from daylight saving time to standard time, // if we convert local time to Universal time, we can have the // following (take PST as an example, bug daylight saving offset is -01:00): // // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 10:00 -9:00 // 02:00 (=> 03:00) 11:00 -9:00 // 03:00 11:00 -8:00 // 04:00 12:00 -8:00 // 05:00 13:00 -8:00 // 06:00 14:00 -8:00 // // So from 02:00 - 02:59:59, we should return the daylight saving offset, instead of the standard offset. // internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes) { if (daylightTimes==null) { return TimeSpan.Zero; } DateTime startTime; DateTime endTime; if (daylightTimes.Delta.Ticks > 0) { startTime = daylightTimes.Start + daylightTimes.Delta; endTime = daylightTimes.End; } else { startTime = daylightTimes.Start; endTime = daylightTimes.End - daylightTimes.Delta; } if (startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. // Note, the summer in the southern hemisphere begins late in the year. if (time < endTime || time >= startTime) { return daylightTimes.Delta; } } else if (time>=startTime && time<endTime) { // In northern hemisphere, the daylight saving time starts in the middle of the year. return daylightTimes.Delta; } return TimeSpan.Zero; }
private static bool IsNonZero(DaylightTime dst) { bool v = false; if ((dst != null) && (dst.Start.CompareTo(dst.End) != 0)) { v = true; } return v; }
/// <summary> /// Returns the daylight saving time period for a particular year. /// </summary> /// <param name="year">The year to which the daylight saving time period applies.</param> /// <returns> /// A <see cref="T:System.Globalization.DaylightTime"></see> instance containing the start and end date for daylight saving time in year. /// </returns> /// <exception cref="T:System.ArgumentOutOfRangeException">year is less than 1 or greater than 9999. </exception> public override DaylightTime GetDaylightChanges(int year) { DaylightTime DLTime = null; if (_bHasDlt) { DateTime StdDay = GetDateTime(_TimeZone.StdDate, year); DateTime DltDay = GetDateTime(_TimeZone.DltDate, year); DLTime = new DaylightTime(DltDay, StdDay, new TimeSpan(0, _TimeZone.DltOffset, 0)); } return DLTime; }
private UTCDate(double tz, DaylightTime dst, DateTime dt) { this.tz = tz; this.dst = dst; this.dt = dt; }
/** * Traverse year and verify dst status. */ private void TestDST(int tz, DaylightTime dst) { DateTime lower = dst.Start; TimeSpan dst_span = dst.Delta; int day = 15; int hour = 12; int min = 0; int sec = 0; for (int i=UTCDate.MONTH_MIN; i<=UTCDate.MONTH_MAX; i++) { // compute dates using UTCDate UTCDate udt = new UTCDate(tz, dst, lower.Year, i, day, hour, min, sec); DateTime dt_utc = udt.ExtractUTC(); DateTime dt_std = udt.ExtractStandard(); DateTime dt_loc = udt.ExtractLocal(); // compute dates manually // utc time -> resolve timezone offset and dst DateTime dt_utc2 = new DateTime(lower.Year, i, day, hour, min, sec, DateTimeKind.Utc); dt_utc2 = dt_utc2.AddHours(-tz); // resolve tz offset if (udt.IsDST) dt_utc2 = dt_utc2.Add(-dst_span); // resolve dst // standard time -> resolve dst only DateTime dt_std2 = new DateTime(lower.Year, i, day, hour, min, sec, DateTimeKind.Local); if (udt.IsDST) dt_std2 = dt_std2.Add(-dst_span); // resolve dst // standard time -> given as input DateTime dt_loc2 = new DateTime(lower.Year, i, day, hour, min, sec, DateTimeKind.Local); Assert.True(dt_utc.CompareTo(dt_utc2) == 0); Assert.True(dt_std.CompareTo(dt_std2) == 0); Assert.True(dt_loc.CompareTo(dt_loc2) == 0); } }