internal long GetUtcOffsetFromUniversalTime(DateTime time, ref bool isAmbiguousLocalDst) { TimeSpan timeSpan = new TimeSpan(this.m_ticksOffset); DaylightTime daylightChanges = this.GetDaylightChanges(time.Year); isAmbiguousLocalDst = false; if (daylightChanges != null) { TimeSpan delta = daylightChanges.Delta; if (delta.Ticks != 0L) { DateTime dateTime1 = daylightChanges.Start - timeSpan; DateTime dateTime2 = daylightChanges.End - timeSpan - daylightChanges.Delta; delta = daylightChanges.Delta; DateTime dateTime3; DateTime dateTime4; if (delta.Ticks > 0L) { dateTime3 = dateTime2 - daylightChanges.Delta; dateTime4 = dateTime2; } else { dateTime3 = dateTime1; dateTime4 = dateTime1 - daylightChanges.Delta; } if (!(dateTime1 > dateTime2) ? time >= dateTime1 && time < dateTime2 : time < dateTime2 || time >= dateTime1) { timeSpan += daylightChanges.Delta; if (time >= dateTime3 && time < dateTime4) { isAmbiguousLocalDst = true; } } return(timeSpan.Ticks); } } return(timeSpan.Ticks); }
private void EST(TimeZone t1) { // It could be EST though... //Assert.AreEqual("Eastern Standard Time", t1.StandardName, "B01"); //Assert.AreEqual("Eastern Daylight Time", t1.DaylightName, "B02"); DaylightTime d1 = t1.GetDaylightChanges(2002); Assert.AreEqual("04/07/2002 02:00:00", d1.Start.ToString("G", CultureInfo.InvariantCulture), "B03"); Assert.AreEqual("10/27/2002 02:00:00", d1.End.ToString("G", CultureInfo.InvariantCulture), "B04"); Assert.AreEqual(36000000000L, d1.Delta.Ticks, "B05"); DaylightTime d2 = t1.GetDaylightChanges(1996); Assert.AreEqual("04/07/1996 02:00:00", d2.Start.ToString("G", CultureInfo.InvariantCulture), "B06"); Assert.AreEqual("10/27/1996 02:00:00", d2.End.ToString("G", CultureInfo.InvariantCulture), "B07"); Assert.AreEqual(36000000000L, d2.Delta.Ticks, "B08"); DateTime d3 = new DateTime(2002, 2, 25); Assert.AreEqual(false, t1.IsDaylightSavingTime(d3), "B09"); DateTime d4 = new DateTime(2002, 4, 8); Assert.AreEqual(true, t1.IsDaylightSavingTime(d4), "B10"); DateTime d5 = new DateTime(2002, 11, 4); Assert.AreEqual(false, t1.IsDaylightSavingTime(d5), "B11"); Assert.AreEqual(-180000000000L, t1.GetUtcOffset(d3).Ticks, "B12"); Assert.AreEqual(-144000000000L, t1.GetUtcOffset(d4).Ticks, "B13"); Assert.AreEqual(-180000000000L, t1.GetUtcOffset(d5).Ticks, "B14"); // Test TimeZone methods with UTC DateTime in DST. DateTime d6 = d4.ToUniversalTime(); Assert.AreEqual(false, t1.IsDaylightSavingTime(d6), "B15"); Assert.AreEqual(0, t1.GetUtcOffset(d6).Ticks, "B16"); }
// // The "lnow" parameter must be the current time, I could have moved // the code here, but I do not want to interfere with serialization // which is why I kept the other constructor around // internal CurrentSystemTimeZone(long lnow) { Int64[] data; string[] names; DateTime now = new DateTime(lnow); if (!GetTimeZoneData(now.Year, out data, out names)) { throw new NotSupportedException(Locale.GetText("Can't get timezone name.")); } m_standardName = Locale.GetText(names[(int)TimeZoneNames.StandardNameIdx]); m_daylightName = Locale.GetText(names[(int)TimeZoneNames.DaylightNameIdx]); m_ticksOffset = data[(int)TimeZoneData.UtcOffsetIdx]; DaylightTime dlt = GetDaylightTimeFromData(data); m_CachedDaylightChanges.Add(now.Year, dlt); OnDeserialization(dlt); }
public void GetUtcOffsetAtDSTBoundary() { /* * Getting a definitive list of timezones which do or don't observe Daylight * Savings is difficult (can't say America's or USA definitively) and lengthy see * * http://en.wikipedia.org/wiki/Daylight_saving_time_by_country * * as a good starting point for a list. * * The following are SOME of the timezones/regions which do support daylight savings. * * Pacific/Auckland * Pacific/Sydney * USA (EST, CST, MST, PST, AKST) note this does not cover all states or regions * Europe/London (GMT) * CET (member states of the European Union) * * This test should work in all the above timezones */ TimeZone tz = TimeZone.CurrentTimeZone; int year = DateTime.Now.Year; DaylightTime daylightChanges = tz.GetDaylightChanges(year); DateTime dst_end = daylightChanges.End; if (dst_end == DateTime.MinValue) { Assert.Ignore(tz.StandardName + " did not observe daylight saving time during " + year + "."); } var standardOffset = tz.GetUtcOffset(daylightChanges.Start.AddMinutes(-1)); var dstOffset = tz.GetUtcOffset(daylightChanges.Start.AddMinutes(1)); // Assert.AreEqual(standardOffset, tz.GetUtcOffset (dst_end)); Assert.AreEqual(dstOffset, tz.GetUtcOffset(dst_end.Add(daylightChanges.Delta.Negate().Add(TimeSpan.FromSeconds(1))))); Assert.AreEqual(dstOffset, tz.GetUtcOffset(dst_end.Add(daylightChanges.Delta.Negate()))); }
// // 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); }
public void TimeZoneInformation() { const string timeFmt = "yyyy-MM-dd HH:mm"; // Get the local time zone and the current local time and year. var localZone = TimeZone.CurrentTimeZone; var currentDate = DateTime.Now; var currentYear = currentDate.Year; Sb.Append(HtmlTableTop("Server Time Zone Information")); // Display the names for standard time and daylight saving time for the local time zone. Sb.Append(HtmlTableRow(true, "Standard time name", localZone.StandardName)); Sb.Append(HtmlTableRow(true, "Daylight saving time name", localZone.DaylightName)); // Display the current date and time and show if they occur in daylight saving time. Sb.Append(HtmlTableRow(true, "Current date and time:", currentDate.ToString(timeFmt))); Sb.Append(HtmlTableRow(true, "Daylight saving time?", localZone.IsDaylightSavingTime(currentDate).ToString())); // Get the current Coordinated Universal Time (UTC) and UTC offset. var currentUtc = localZone.ToUniversalTime(currentDate); var currentOffset = localZone.GetUtcOffset(currentDate); Sb.Append(HtmlTableRow(true, "Coordinated Universal Time", currentUtc.ToString(timeFmt))); Sb.Append(HtmlTableRow(true, "UTC offset", currentOffset.ToString())); // Get the DaylightTime object for the current year. DaylightTime daylight = localZone.GetDaylightChanges(currentYear); // Display the daylight saving time range for the current year. Sb.Append(HtmlTableRow(true, String.Format("Daylight saving time {0} Start", currentYear), daylight.Start.ToString(timeFmt))); Sb.Append(HtmlTableRow(true, String.Format("Daylight saving time {0} End", currentYear), daylight.End.ToString(timeFmt))); Sb.Append(HtmlTableRow(true, String.Format("Daylight saving time {0} Delta", currentYear), daylight.Delta.ToString())); Sb.Append(HtmlTableBottom); }
internal long GetUtcOffsetFromUniversalTime(DateTime time) { // Get the daylight changes for the year of the specified time. DaylightTime daylightTime = GetDaylightChanges(time.Year); // This is the UTC offset for the time (which is based on Universal time), but it is calculated according to local timezone rule. long utcOffset = TimeZone.CalculateUtcOffset(time, daylightTime).Ticks + m_ticksOffset; long ticks = time.Ticks; if (daylightTime.Delta.Ticks != 0) { // This timezone uses daylight saving rules. if (m_ticksOffset < 0) { // This deals with GMT-XX timezones (e.g. Pacific Standard time). if ((ticks >= daylightTime.Start.Ticks + daylightTime.Delta.Ticks) && (ticks < daylightTime.Start.Ticks - m_ticksOffset)) { return(utcOffset - daylightTime.Delta.Ticks); } if ((ticks >= daylightTime.End.Ticks) && (ticks < daylightTime.End.Ticks - m_ticksOffset - daylightTime.Delta.Ticks)) { return(utcOffset + daylightTime.Delta.Ticks); } } else { // This deals with GMT+XX timezones. if ((ticks >= daylightTime.Start.Ticks - m_ticksOffset) && (ticks < daylightTime.Start.Ticks + daylightTime.Delta.Ticks)) { return(utcOffset + daylightTime.Delta.Ticks); } if ((ticks >= daylightTime.End.Ticks - m_ticksOffset - daylightTime.Delta.Ticks) && (ticks < daylightTime.End.Ticks)) { return(utcOffset - daylightTime.Delta.Ticks); } } } return(utcOffset); }
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; }
/// <summary>Returns a value indicating whether the specified date and time is within the specified daylight saving time period.</summary> /// <returns>true if <paramref name="time" /> is in <paramref name="daylightTimes" />; otherwise, false.</returns> /// <param name="time">A date and time. </param> /// <param name="daylightTimes">A daylight saving time period. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="daylightTimes" /> is null. </exception> /// <filterpriority>1</filterpriority> public static bool IsDaylightSavingTime(DateTime time, DaylightTime daylightTimes) { if (daylightTimes == null) { throw new ArgumentNullException("daylightTimes"); } if (daylightTimes.Start.Ticks == daylightTimes.End.Ticks) { return(false); } if (daylightTimes.Start.Ticks < daylightTimes.End.Ticks) { if (daylightTimes.Start.Ticks < time.Ticks && daylightTimes.End.Ticks > time.Ticks) { return(true); } } else if (time.Year == daylightTimes.Start.Year && time.Year == daylightTimes.End.Year && (time.Ticks < daylightTimes.End.Ticks || time.Ticks > daylightTimes.Start.Ticks)) { return(true); } return(false); }
// // This routine is intended to be called by GetLocalTimeDiff(DatetTime) // or by ToLocalTime after validation has been performed // // time is the time to map, utc_offset is the utc_offset that // has been computed for calling GetUtcOffset on time. // // When called by GetLocalTime, utc_offset is assumed to come // from a time constructed by new DateTime (DateTime.GetNow ()), that // is a valid time. // // When called by ToLocalTime ranges are checked before this is // called. // internal TimeSpan GetLocalTimeDiff(DateTime time, TimeSpan utc_offset) { DaylightTime dlt = GetDaylightChanges(time.Year); if (dlt.Delta.Ticks == 0) { return(utc_offset); } DateTime local = time.Add(utc_offset); if (local < dlt.End && dlt.End.Subtract(dlt.Delta) <= local) { return(utc_offset); } if (local >= dlt.Start && dlt.Start.Add(dlt.Delta) > local) { return(utc_offset - dlt.Delta); } return(GetUtcOffset(local)); }
private void NZST(TimeZone t1) { Assert.AreEqual("NZST", t1.StandardName, "E01"); Assert.AreEqual("NZDT", t1.DaylightName, "E02"); DaylightTime d1 = t1.GetDaylightChanges(2013); Assert.AreEqual("09/29/2013 02:00:00", d1.Start.ToString("G", CultureInfo.InvariantCulture), "E03"); Assert.AreEqual("04/07/2013 03:00:00", d1.End.ToString("G", CultureInfo.InvariantCulture), "E04"); Assert.AreEqual(36000000000L, d1.Delta.Ticks, "E05"); DaylightTime d2 = t1.GetDaylightChanges(2001); Assert.AreEqual("10/07/2001 02:00:00", d2.Start.ToString("G", CultureInfo.InvariantCulture), "E06"); Assert.AreEqual("03/18/2001 03:00:00", d2.End.ToString("G", CultureInfo.InvariantCulture), "E07"); Assert.AreEqual(36000000000L, d2.Delta.Ticks, "E08"); DateTime d3 = new DateTime(2013, 02, 15); Assert.AreEqual(true, t1.IsDaylightSavingTime(d3), "E09"); DateTime d4 = new DateTime(2013, 04, 30); Assert.AreEqual(false, t1.IsDaylightSavingTime(d4), "E10"); DateTime d5 = new DateTime(2013, 11, 03); Assert.AreEqual(true, t1.IsDaylightSavingTime(d5), "E11"); Assert.AreEqual(36000000000L /*hour*/ * 13L, t1.GetUtcOffset(d3).Ticks, "E12"); Assert.AreEqual(36000000000L /*hour*/ * 12L, t1.GetUtcOffset(d4).Ticks, "E13"); Assert.AreEqual(36000000000L /*hour*/ * 13L, t1.GetUtcOffset(d5).Ticks, "E14"); // Test TimeZone methods with UTC DateTime in DST. DateTime d6 = d5.ToUniversalTime(); Assert.AreEqual(false, t1.IsDaylightSavingTime(d6), "E15"); Assert.AreEqual(0, t1.GetUtcOffset(d6).Ticks, "E16"); }
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)) { object internalSyncObject = CurrentSystemTimeZone.InternalSyncObject; lock (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]); }
private void CET(TimeZone t1) { Assert.IsTrue("CET" == t1.StandardName || "W. Europe Standard Time" == t1.StandardName, "A01"); Assert.IsTrue("CEST" == t1.DaylightName || "W. Europe Daylight Time" == t1.DaylightName, "A02"); DaylightTime d1 = t1.GetDaylightChanges(2002); Assert.AreEqual("03/31/2002 02:00:00", d1.Start.ToString("G", CultureInfo.InvariantCulture), "A03"); Assert.AreEqual("10/27/2002 03:00:00", d1.End.ToString("G", CultureInfo.InvariantCulture), "A04"); Assert.AreEqual(36000000000L, d1.Delta.Ticks, "A05"); DaylightTime d2 = t1.GetDaylightChanges(1996); Assert.AreEqual("03/31/1996 02:00:00", d2.Start.ToString("G", CultureInfo.InvariantCulture), "A06"); Assert.AreEqual("10/27/1996 03:00:00", d2.End.ToString("G", CultureInfo.InvariantCulture), "A07"); Assert.AreEqual(36000000000L, d2.Delta.Ticks, "A08"); DateTime d3 = new DateTime(2002, 2, 25); Assert.AreEqual(false, t1.IsDaylightSavingTime(d3), "A09"); DateTime d4 = new DateTime(2002, 4, 2); Assert.AreEqual(true, t1.IsDaylightSavingTime(d4), "A10"); DateTime d5 = new DateTime(2002, 11, 4); Assert.AreEqual(false, t1.IsDaylightSavingTime(d5), "A11"); Assert.AreEqual(36000000000L, t1.GetUtcOffset(d3).Ticks, "A12"); Assert.AreEqual(72000000000L, t1.GetUtcOffset(d4).Ticks, "A13"); Assert.AreEqual(36000000000L, t1.GetUtcOffset(d5).Ticks, "A14"); // Test TimeZone methods with UTC DateTime in DST. DateTime d6 = d4.ToUniversalTime(); Assert.AreEqual(false, t1.IsDaylightSavingTime(d6), "A15"); Assert.AreEqual(0, t1.GetUtcOffset(d6).Ticks, "A16"); }
// 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 DaylightTime GetDaylightChanges(int inYear) { TimeZoneInfo.AdjustmentRule ruleFound = null; TimeZoneInfo.AdjustmentRule[] adjustments = TimeZoneInfo.GetAdjustmentRules(); if (adjustments.Length == 0) { return(null); // No Daylighttime. } //Find the correct adjustment rule ruleFound = adjustments.SingleOrDefault(a => a.DateStart.Year <= inYear && a.DateEnd.Year >= inYear); if (null == ruleFound) { return(null); } DaylightTime outDaylightTime = new DaylightTime( GetDateTime(inYear, ruleFound.DaylightTransitionStart) , GetDateTime(inYear, ruleFound.DaylightTransitionEnd) , ruleFound.DaylightDelta); return(outDaylightTime); }
/// <summary> /// using System.Reflection; /// Version Text로부터 Build된 일시를 구합니다. /// AssemblyInfo.cs의 빌드 버전을 1.0.*로 변경하세요. /// </summary> /// <param name="asm">Assembly.GetExecutingAssembly()를 호출하여 전달하세요</param> /// <returns>Build DateTime 빌드 날짜</returns> static public DateTime GetBuildTime(Assembly asm) { Version v = asm.GetName().Version; //int majorV = v.Major; //주버전 //int minorV = v.Minor; //부버전 int buildV = v.Build; //빌드번호(2000.01.01 부터 Build 된 날짜 까지의 총 일 수) int revisionV = v.Revision; //수정번호(자정 0시부터 Build 된 시간까지의 총 시간(Sec)) //빌드번호는 2000년 1월 1일 부터 Build 된 날짜 까지의 총 일수 이다. DateTime dtBuildDate = new DateTime(2000, 1, 1).AddDays(buildV); //수정번호는 자정(0시) 부터 Build 된 시간까지 지나간 시간(Sec) 이다. dtBuildDate = dtBuildDate.AddSeconds(revisionV * 2); //시차조정 DaylightTime dayLight = TimeZone.CurrentTimeZone.GetDaylightChanges(dtBuildDate.Year); if (TimeZone.IsDaylightSavingTime(dtBuildDate, dayLight)) { dtBuildDate = dtBuildDate.Add(dayLight.Delta); } return(dtBuildDate); }
// Methods public override DaylightTime GetDaylightChanges(int year) { if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", year + Locale.GetText(" is not in a range between 1 and 9999.")); } // // First we try the case for this year, very common, and is used // by DateTime.Now (a popular call) indirectly. // if (year == this_year) { return(this_year_dlt); } lock (m_CachedDaylightChanges) { DaylightTime dlt = (DaylightTime)m_CachedDaylightChanges [year]; if (dlt == null) { Int64[] data; string[] names; if (!GetTimeZoneData(year, out data, out names)) { throw new ArgumentException(Locale.GetText("Can't get timezone data for " + year)); } dlt = GetDaylightTimeFromData(data); m_CachedDaylightChanges.Add(year, dlt); } return(dlt); } }
private void FormInfo_Load(object sender, EventArgs e) { TimeZone localZone = TimeZone.CurrentTimeZone; DaylightTime daylight = localZone.GetDaylightChanges(DateTime.Now.Year); this.textBox.Text = "Timezone: " + localZone.StandardName + " \r\nDaylight saving time name: " + localZone.DaylightName + " \r\nDaylight saving time: " + localZone.IsDaylightSavingTime(DateTime.Now) + " \r\nDaylight start: " + daylight.Start.ToString() + " \r\nDaylight end: " + daylight.End.ToString() + " \r\nDelta: " + daylight.Delta + " \r\nUTC time: " + localZone.ToUniversalTime(DateTime.Now) + " \r\nUTC offset: " + localZone.GetUtcOffset(DateTime.Now) ; this.textBox.SelectionStart = 0; this.textBox.SelectionLength = 0; }
/// <summary> /// Version Text로부터 Build된 일시를 구합니다. /// </summary> /// <returns></returns> public static DateTime getBuildDateTime() { //1. Assembly.GetExecutingAssembly().FullName의 값은 //'ApplicationName, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' //와 같다. string strVersionText = Assembly.GetExecutingAssembly().FullName .Split(',')[1] .Trim() .Split('=')[1]; //2. Version Text의 세번째 값(Build Number)은 2000년 1월 1일부터 //Build된 날짜까지의 총 일(Days) 수 이다. int intDays = Convert.ToInt32(strVersionText.Split('.')[2]); DateTime refDate = new DateTime(2000, 1, 1); DateTime dtBuildDate = refDate.AddDays(intDays); //3. Verion Text의 네번째 값(Revision NUmber)은 자정으로부터 Build된 //시간까지의 지나간 초(Second) 값 이다. int intSeconds = Convert.ToInt32(strVersionText.Split('.')[3]); intSeconds = intSeconds * 2; dtBuildDate = dtBuildDate.AddSeconds(intSeconds); //4. 시차조정 DaylightTime daylingTime = TimeZone.CurrentTimeZone .GetDaylightChanges(dtBuildDate.Year); if (TimeZone.IsDaylightSavingTime(dtBuildDate, daylingTime)) { dtBuildDate = dtBuildDate.Add(daylingTime.Delta); } return(dtBuildDate); }
/// <summary> /// Returns the daylight saving time period for a particular year. /// </summary> public override DaylightTime GetDaylightChanges(int year) { if (m_info.DaylightDate.wMonth == 0) { // No daylight savings in this time zone return(new DaylightTime(System.DateTime.MinValue, System.DateTime.MinValue, System.TimeSpan.Zero)); } else { // Look up result in the cache. DaylightTime result = null; if (m_cachedDaylightChanges != null) { result = (DaylightTime)m_cachedDaylightChanges[year]; } if (result == null) { // Calculate daylight savings from the stored time zone information result = new DaylightTime(GetChangeDateTime(m_info.DaylightDate, year), GetChangeDateTime(m_info.StandardDate, year), new System.TimeSpan(0, m_info.DaylightBias * -1, 0)); if (m_cachedDaylightChanges == null) { m_cachedDaylightChanges = new Hashtable(); } m_cachedDaylightChanges.Add(year, result); } return(result); } }
public static string GetDateWithFormat(string dt, string timeZone = "") { DateTime convertedDateTime; var isValidFormat = DateTime.TryParse(dt, out convertedDateTime); if (isValidFormat) { if (!String.IsNullOrEmpty(timeZone)) { TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone); dt = TimeZoneInfo.ConvertTimeFromUtc(convertedDateTime, timeInfo).ToString("MM/dd/yyyy"); } else { TimeZone localZone = TimeZone.CurrentTimeZone; TimeSpan currentOffset = localZone.GetUtcOffset(convertedDateTime); DaylightTime daylight = localZone.GetDaylightChanges(convertedDateTime.Year); convertedDateTime = convertedDateTime.Add(currentOffset); //convertedDateTime = convertedDateTime.Add(daylight.Delta); // If required then later we can add return(convertedDateTime.ToString("MM/dd/yyyy")); } } return(dt); }
public DateTime GetBuildDataTime(Version oVersion) { string strVersion = oVersion.ToString(); //날짜 등록 int iDays = Convert.ToInt32(strVersion.Split('.')[2]); DateTime refData = new DateTime(2000, 1, 1); DateTime dtBuildDate = refData.AddDays(iDays); //초 등록 int iSeconds = Convert.ToInt32(strVersion.Split('.')[3]); iSeconds = iSeconds * 2; dtBuildDate = dtBuildDate.AddSeconds(iSeconds); //시차 조정 DaylightTime daylighttime = TimeZone.CurrentTimeZone.GetDaylightChanges(dtBuildDate.Year); if (TimeZone.IsDaylightSavingTime(dtBuildDate, daylighttime)) { dtBuildDate = dtBuildDate.Add(daylighttime.Delta); } return(dtBuildDate); }
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); }
private long GetUtcOffsetFromUniversalTime(DateTime time) { object Year = time.Year; if (!_cachedDaylightChanges.ContainsKey(Year)) { lock (this) { if (!_cachedDaylightChanges.ContainsKey(Year)) { if (this.DaylightMonth == 0 || this.StandardMonth == 0) { _cachedDaylightChanges.Add(Year, new DaylightTime(DateTime.MinValue, DateTime.MaxValue, new TimeSpan(0, 0, -(this.Bias), 0, 0))); } else if (this.DaylightMonth < this.StandardMonth) { DateTime startDaylight = new DateTime(time.Year, this.DaylightMonth, 1, this.DaylightHour /*-(this.StandardBias+this.DaylightBias)/60*/, 0, 0, 0); DateTime endDaylight = new DateTime(time.Year, this.StandardMonth, 1, this.StandardHour, 0, 0, 0); // Calculate Real Day [6/18/2004] startDaylight = TransformDate(startDaylight, this.DaylightWeek, (DayOfWeek)this.DaylightDayOfWeek); endDaylight = TransformDate(endDaylight, this.StandardWeek, (DayOfWeek)this.StandardDayOfWeek); startDaylight = startDaylight.AddMinutes((this.Bias + this.StandardBias)); endDaylight = endDaylight.AddMinutes((this.Bias + this.DaylightBias)); _cachedDaylightChanges.Add(Year, new DaylightTime(startDaylight, endDaylight, new TimeSpan(0, 0, -(this.Bias + this.DaylightBias), 0, 0))); } else { DateTime startStandard = new DateTime(time.Year, this.StandardMonth, 1, this.StandardHour, 0, 0, 0); DateTime endStandard = new DateTime(time.Year, this.DaylightMonth, 1, this.DaylightHour /*-(this.StandardBias+this.DaylightBias)/60*/, 0, 0, 0); // Calculate Real Day [6/18/2004] startStandard = TransformDate(startStandard, this.StandardWeek, (DayOfWeek)this.StandardDayOfWeek); endStandard = TransformDate(endStandard, this.DaylightWeek, (DayOfWeek)this.DaylightDayOfWeek); startStandard = startStandard.AddMinutes((this.Bias + this.DaylightBias)); endStandard = endStandard.AddMinutes((this.Bias + this.StandardBias)); _cachedDaylightChanges.Add(Year, new DaylightTime(endStandard, startStandard, new TimeSpan(0, 0, -(this.Bias + this.DaylightBias), 0, 0))); } } } } DaylightTime daylightTime = (DaylightTime)_cachedDaylightChanges[Year]; if (daylightTime.Start < daylightTime.End) { if (time < daylightTime.Start || time > daylightTime.End) { // Standard Time return((long)-1 * (long)this.Bias * (long)600000000); } else { // Daylight Time return(daylightTime.Delta.Ticks); } } else { if (time < daylightTime.End || time > daylightTime.Start) { // Standard Time return(daylightTime.Delta.Ticks); } else { // Daylight Time return((long)-1 * (long)this.Bias * (long)600000000); } } }
/// <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 is in ; otherwise, false.</returns> public static Boolean IsDaylightSavingTime(this DateTime time, DaylightTime daylightTimes) { return(TimeZone.IsDaylightSavingTime(time, daylightTimes)); }
// // 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; } bool 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); }
// 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); }
public static void Main(String[] args) { Int64[] data; string[] names; if (!System.CurrentSystemTimeZone.GetTimeZoneData(DateTime.Now.Year, out data, out names)) { throw new NotSupportedException("Can't get timezone name."); } TimeSpan utcOffsetTS = TimeSpan.FromTicks(data[(int)TimeZoneData.UtcOffsetIdx]); char utcOffsetSign = (utcOffsetTS >= TimeSpan.Zero) ? '+' : '-'; string displayName = "(GMT" + utcOffsetSign + utcOffsetTS.ToString(@"hh\:mm") + ") Local Time"; string standardDisplayName = names[(int)TimeZoneNames.StandardNameIdx]; string daylightDisplayName = names[(int)TimeZoneNames.DaylightNameIdx]; //Create The Adjustment Rules For This TimeZoneInfo. var adjustmentList = new List <TimeZoneInfo.AdjustmentRule>(); for (int year = 1970; year <= 2037; year++) { if (!System.CurrentSystemTimeZone.GetTimeZoneData(year, out data, out names)) { throw new NotSupportedException("Can't get timezone name."); } DaylightTime dlt = new DaylightTime(new DateTime(data[(int)TimeZoneData.DaylightSavingStartIdx]), new DateTime(data[(int)TimeZoneData.DaylightSavingEndIdx]), new TimeSpan(data[(int)TimeZoneData.AdditionalDaylightOffsetIdx])); DateTime dltStartTime = new DateTime(1, 1, 1).Add(dlt.Start.TimeOfDay); DateTime dltEndTime = new DateTime(1, 1, 1).Add(dlt.End.TimeOfDay); TimeZoneInfo.TransitionTime startTime = TimeZoneInfo.TransitionTime.CreateFixedDateRule(dltStartTime, dlt.Start.Month, dlt.Start.Day); TimeZoneInfo.TransitionTime endTime = TimeZoneInfo.TransitionTime.CreateFixedDateRule(dltEndTime, dlt.End.Month, dlt.End.Day); //mktime only supports dates starting in 1970, so create an adjustment rule for years before 1970 following 1970s rules if (year == 1970) { TimeZoneInfo.AdjustmentRule firstRule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue, new DateTime(1969, 12, 31), dlt.Delta, startTime, endTime); adjustmentList.Add(firstRule); } TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(year, 1, 1), new DateTime(year, 12, 31), dlt.Delta, startTime, endTime); adjustmentList.Add(rule); //mktime only supports dates up to 2037, so create an adjustment rule for years after 2037 following 2037s rules if (year == 2037) { TimeZoneInfo.AdjustmentRule lastRule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2038, 1, 1), DateTime.MaxValue, dlt.Delta, startTime, endTime); adjustmentList.Add(lastRule); } } TimeZoneInfo local = TimeZoneInfo.CreateCustomTimeZone("local", utcOffsetTS, displayName, standardDisplayName, daylightDisplayName, adjustmentList.ToArray(), false); //Set the C# library's local time field via reflection FieldInfo cachedStaticData = typeof(TimeZoneInfo).GetField("s_cachedData", BindingFlags.Static | BindingFlags.NonPublic); Object cachedData = cachedStaticData.GetValue(null); FieldInfo localTzField = cachedData.GetType().GetField("m_localTimeZone", BindingFlags.Instance | BindingFlags.NonPublic); Console.WriteLine("UTC: " + DateTime.UtcNow); Console.WriteLine("LOCAL: " + DateTime.Now); //Set the local time to UTC...simulates a device that does not currently support TimeZoneInfo localTzField.SetValue(cachedData, TimeZoneInfo.Utc); Console.WriteLine("UTC To Local Time Fails: " + DateTime.UtcNow.ToLocalTime()); Console.WriteLine("DateTime.Now Fails: " + DateTime.Now); //Set the local time to our created one localTzField.SetValue(cachedData, local); Console.WriteLine("UTC To Local Time Success: " + DateTime.UtcNow.ToLocalTime()); Console.WriteLine("DateTime.Now Success: " + DateTime.Now); //Created Custom Timezone can also be used for conversion without reflection Console.WriteLine("UTC To Local Time Success No Reflection: " + TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, local)); }
/// <summary>Returns a value indicating whether the specified date and time is within the specified daylight saving time period.</summary><returns>true if <paramref name="time" /> is in <paramref name="daylightTimes" />; otherwise, false.</returns><param name="time">A date and time. </param><param name="daylightTimes">A daylight saving time period. </param><exception cref="T:System.ArgumentNullException"><paramref name="daylightTimes" /> is null. </exception><filterpriority>1</filterpriority> public static bool IsDaylightSavingTime(DateTime time, DaylightTime daylightTimes) { throw new NotImplementedException(); }
public override DaylightTime GetDaylightChanges(int year) { if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", String.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, 9999)); } Object objYear = (Object)year; if (!m_CachedDaylightChanges.Contains(objYear)) { BCLDebug.Log("Getting TimeZone information for: " + objYear); lock (typeof(CurrentSystemTimeZone)) { 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(); 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[1], rawData[2], rawData[3], rawData[4], rawData[5], rawData[6], rawData[7]); // // Store the end of daylight saving time. // end = GetDayOfWeek(year, 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); }
/// <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 is in ; otherwise, false.</returns> public static Boolean IsDaylightSavingTime(this DateTime time, DaylightTime daylightTimes) { return TimeZone.IsDaylightSavingTime(time, daylightTimes); }