public Window1() { InitializeComponent(); Calendar mdCalendar = new Calendar(); DateTime date = DateTime.Now; TimeZone time = TimeZone.CurrentTimeZone; TimeSpan difference = time.GetUtcOffset(date); timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; }
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"); }
public static long ToUnixTimeMs(this DateTime dateTime) { var dtUtc = dateTime; if (dateTime.Kind != DateTimeKind.Utc) { dtUtc = dateTime.Kind == DateTimeKind.Unspecified && dateTime > DateTime.MinValue ? DateTime.SpecifyKind(dateTime.Subtract(LocalTimeZone.GetUtcOffset(dateTime)), DateTimeKind.Utc) : dateTime.ToStableUniversalTime(); } return((long)(dtUtc.Subtract(UnixEpochDateTimeUtc)).TotalMilliseconds); }
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()))); }
/// <summary> /// Creates the date time offset. /// </summary> /// <param name="year">The year.</param> /// <param name="month">The month, default 1 (January).</param> /// <param name="date">The date, default 1.</param> /// <param name="hour">The hour, default 0 (12 am).</param> /// <param name="minute">The minute, default 0.</param> /// <param name="second">The second, default 0.</param> /// <param name="millisecond">The millisecond, default 0.</param> /// <returns>DateTimeOffset.</returns> public DateTimeOffset CreateDateTimeOffset(int year, int month = 1, int date = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0) { millisecond = SetValue(millisecond, 0, 1000, second, s => second = s); second = SetValue(second, 0, 60, minute, m => minute = m); minute = SetValue(minute, 0, 60, hour, h => hour = h); hour = SetValue(hour, 0, 24, date, d => date = d); date = SetValue(date, 1, () => DateTime.DaysInMonth(year, month), month, m => month = SetValue(m, 1, 12, year, y => year = y)); var dt = new DateTime(year, month, date, hour, minute, second, millisecond, DateTimeKind.Unspecified); var utc = TimeZone.GetUtcOffset(dt); return(new DateTimeOffset(dt, utc)); }
public static double GetTimeZoneOffset() { TimeZone zone = TimeZone.CurrentTimeZone; TimeZoneInfo eastern; DateTime dtNow = DateTime.Now; eastern = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); TimeSpan localOffset = zone.GetUtcOffset(dtNow); TimeSpan easternOffset = eastern.GetUtcOffset(dtNow); TimeSpan diff = easternOffset - localOffset; return(diff.TotalHours); }
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here lCulture.Text = "Culture:" + Thread.CurrentThread.CurrentCulture + " UICulture:" + Thread.CurrentThread.CurrentUICulture; if (lUTCNow != null) { lUTCNow.Text = DateTime.UtcNow.ToString(); } if (lTimeZone != null) { TimeZone tz = TimeZone.CurrentTimeZone; lTimeZone.Text = tz.StandardName + ";" + tz.GetUtcOffset(DateTime.Now); } }
static void main(string[] args) { const string dataFmt = "{0,-30}{1}"; const string timeFmt = "{0,-30}{1:yyyy-MM-dd HH:mm}"; Console.WriteLine( "This example of selected TimeZone class " + "elements generates the following \n" + "output, which varies depending on the " + "time zone in which it is run.\n"); // Get the local time zone and the current local time and year. TimeZone localZone = TimeZone.CurrentTimeZone; DateTime currentDate = DateTime.Now; int currentYear = currentDate.Year; // Display the names for standard time and daylight saving // time for the local time zone. Console.WriteLine(dataFmt, "Standard time name:", localZone.StandardName); Console.WriteLine(dataFmt, "Daylight saving time name:", localZone.DaylightName); // Display the current date and time and show if they occur // in daylight saving time. Console.WriteLine("\n" + timeFmt, "Current date and time:", currentDate); Console.WriteLine(dataFmt, "Daylight saving time?", localZone.IsDaylightSavingTime(currentDate)); // Get the current Coordinated Universal Time (UTC) and UTC // offset. DateTime currentUTC = localZone.ToUniversalTime(currentDate); TimeSpan currentOffset = localZone.GetUtcOffset(currentDate); Console.WriteLine(timeFmt, "Coordinated Universal Time:", currentUTC); Console.WriteLine(dataFmt, "UTC offset:", currentOffset); // Get the DaylightTime object for the current year. DaylightTime daylight = localZone.GetDaylightChanges(currentYear); // Display the daylight saving time range for the current year. Console.WriteLine("\nDaylight saving time for year {0}:", currentYear); Console.WriteLine("{0:yyyy-MM-dd HH:mm} to " + "{1:yyyy-MM-dd HH:mm}, delta: {2}", daylight.Start, daylight.End, daylight.Delta); }
/// <summary> /// Returns true if the specified DayEntry is within the same month as <c>month</c>; /// </summary> /// <param name="dayEntry"></param> /// <param name="timeZone"></param> /// <param name="month"></param> /// <returns></returns> public static bool OccursInMonth(DayEntry dayEntry, TimeZone timeZone, DateTime month) { DateTime startOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0); DateTime endOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0); endOfMonth = endOfMonth.AddMonths(1); endOfMonth = endOfMonth.AddSeconds(-1); TimeSpan offset = timeZone.GetUtcOffset(endOfMonth); endOfMonth = endOfMonth.AddHours(offset.Negate().Hours); return(OccursBetween(dayEntry, timeZone, startOfMonth, endOfMonth)); }
public EnvInfo GetEnvInfo() { var name = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast <ManagementObject>() select x.GetPropertyValue("Caption")).FirstOrDefault(); var time = DateTime.Now; TimeZone localZone = TimeZone.CurrentTimeZone; string zone = localZone.StandardName; string utcOffset = localZone.GetUtcOffset(time).TotalHours.ToString(); var timeInfo = new EnvTimeInfo(String.Format(timeFmt, time), zone, utcOffset); return(name != null ? new EnvInfo(name.ToString(), timeInfo) : new EnvInfo("Unknown", timeInfo)); }
override protected void Convert(TextWriter writer, object state) { TimeSpan delta = (TimeSpan.Zero); try { TimeZone TimeZoneInfo = TimeZone.CurrentTimeZone; delta = TimeZoneInfo.GetUtcOffset(DateTime.Now); } catch { } writer.Write(delta.TotalMinutes.ToString()); }
static void DisplayTime(DateTime time, TimeZone zone) { Console.WriteLine(string.Format("Current time zone is {0}", zone.StandardName)); Console.WriteLine(string.Format("Does this time include Daylight saving? - {0}", zone.IsDaylightSavingTime(time) ? "Yes" : "No")); if (zone.IsDaylightSavingTime(time)) { Console.WriteLine(string.Format("So this time locally is {0} {1}", time.ToShortTimeString(), zone.DaylightName)); } else { Console.WriteLine(string.Format("So this time locally is {0} {1}", time.ToShortTimeString(), zone.StandardName)); } Console.WriteLine(string.Format("Time offset from UTC is {0} hours.", zone.GetUtcOffset(time))); }
/// <summary> /// Generate the date string /// </summary> /// <returns>A RFC-2822 error code</returns> public override String ToString() { TimeZone current = TimeZone.CurrentTimeZone; TimeSpan timespan = current.GetUtcOffset(_datetime); String tz = String.Format("{0:00}{1:00}", timespan.Hours, Math.Abs(timespan.Minutes % 60)); if (timespan.TotalHours >= 0) { tz = "+" + tz; } // Note: fixed for non-English default cultures; thanks, Angel Marin return(_datetime.ToString("ddd, d MMM yyyy HH:mm:ss " + tz, System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat)); }
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"); }
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"); }
public static void WriteWcfJsonDate(TextWriter writer, DateTime dateTime) { if (JsConfig.AssumeUtc && dateTime.Kind == DateTimeKind.Unspecified) { dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); } if (JsConfig.DateHandler == JsonDateHandler.ISO8601) { writer.Write(dateTime.ToString("o", CultureInfo.InvariantCulture)); return; } var timestamp = dateTime.ToUnixTimeMs(); string offset = null; if (dateTime.Kind != DateTimeKind.Utc) { if (JsConfig.DateHandler == JsonDateHandler.TimestampOffset && dateTime.Kind == DateTimeKind.Unspecified) { offset = UnspecifiedOffset; } else #if NET20 || PLATFORM_USE_AOT { offset = LocalZone.GetUtcOffset(dateTime).ToTimeOffsetString(); } #else { offset = LocalTimeZone.GetUtcOffset(dateTime).ToTimeOffsetString(); } #endif } else { // Normally the JsonDateHandler.TimestampOffset doesn't append an offset for Utc dates, but if // the JsConfig.AppendUtcOffset is set then we will if (JsConfig.DateHandler == JsonDateHandler.TimestampOffset && JsConfig.AppendUtcOffset.HasValue && JsConfig.AppendUtcOffset.Value) { offset = UtcOffset; } } writer.Write(EscapedWcfJsonPrefix); writer.Write(timestamp); if (offset != null) { writer.Write(offset); } writer.Write(EscapedWcfJsonSuffix); }
public MainWindow() { InitializeComponent(); MDCalendar mdCalendar = new MDCalendar(); DateTime date = DateTime.Now; TimeZone time = TimeZone.CurrentTimeZone; TimeSpan difference = time.GetUtcOffset(date); uint currentTime = mdCalendar.Time() + (uint)difference.TotalSeconds; //persianCalendar.Content = mdCalendar.Date("Y/m/D W", currentTime, true); christianityCalendar.Content = mdCalendar.Date("P Z/e/d", currentTime, false); timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; }
public int Compare(object x, object y) { ShardProfile shard = null; ShardProfile profile2 = null; if (x is GShardMenu) { shard = ((GShardMenu)x).Shard; } else { shard = x as ShardProfile; } if (y is GShardMenu) { profile2 = ((GShardMenu)y).Shard; } else { profile2 = y as ShardProfile; } if (shard == null) { return(1); } if (profile2 == null) { return(-1); } TimeZone currentTimeZone = TimeZone.CurrentTimeZone; DateTime now = DateTime.Now; int hours = currentTimeZone.GetUtcOffset(now).Hours; int num2 = -shard.TimeZone; int num3 = -profile2.TimeZone; int num4 = Math.Abs((int)(hours - num2)); int num5 = Math.Abs((int)(hours - num3)); int num6 = num4 - num5; if (num6 == 0) { num6 = shard.Name.CompareTo(profile2.Name); if (num6 == 0) { num6 = shard.Index - profile2.Index; } } return(num6); }
public static OracleTimeStampTZ ToOracleTimestamp(DateTime value) { if (value.Kind == DateTimeKind.Utc) { return(new OracleTimeStampTZ(value, "UTC")); } if (TimeZoneWithDaylightSaving == null) { return(new OracleTimeStampTZ(value, CurrentZone.GetUtcOffset(value).ToString())); } else if (LocalZoneInfo.IsDaylightSavingTime(value)) { return(new OracleTimeStampTZ(value, TimeZoneWithDaylightSaving)); } return(new OracleTimeStampTZ(value, TimeZoneWithoutDaylightSaving)); }
public EyeClock() { InitializeComponent(); IsraelCalendar mdCalendar = new IsraelCalendar(); DateTime date = DateTime.Now; TimeZone time = TimeZone.CurrentTimeZone; TimeSpan difference = time.GetUtcOffset(date); //uint currentTime = mdCalendar.Time() + (uint)difference.TotalSeconds; uint currentTime = (uint)mdCalendar.GetIsraelTime().Second + (uint)difference.TotalSeconds; christianityCalendar.Content = mdCalendar.GetIsraelTime(); timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; }
public static DateTime GetToday() { TimeZone localZone = TimeZone.CurrentTimeZone; TimeSpan currentOffset = localZone.GetUtcOffset(DateTime.Now); double userTimeOffset = GetUserTimeOffset(); double secDiff = ((-1) * currentOffset.TotalSeconds) + userTimeOffset; DateTime userToday = DateTime.Now.AddSeconds(secDiff); DateTime today = userToday.Date.AddSeconds((-1) * userTimeOffset); logger.Info("Time different : " + secDiff); logger.Info("User Today : " + userToday.ToString()); logger.Info("UTC Today : " + today.ToString()); return(today); }
public static DateTime GetDateTime(DateTime dt, string timeZone = "") { if (!String.IsNullOrEmpty(timeZone)) { TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone); dt = TimeZoneInfo.ConvertTimeFromUtc(dt, timeInfo); } else { TimeZone localZone = TimeZone.CurrentTimeZone; TimeSpan currentOffset = localZone.GetUtcOffset(dt); DaylightTime daylight = localZone.GetDaylightChanges(dt.Year); dt = dt.Add(currentOffset); } return(dt); }
private static string GetUserTimeZone() { DateTime currentDate = DateTime.Now; TimeZone localZone = TimeZone.CurrentTimeZone; DateTime currentUTC = localZone.ToUniversalTime(currentDate); TimeSpan currentOffset = localZone.GetUtcOffset(currentDate); // const string dataFmt = "{0,-30}{1}"; // const string timeFmt = "{0,-30}{1:yyyy-MM-dd HH:mm}"; string s = currentUTC.ToString(); s = s + " "; s = s + currentOffset.ToString(); return(s); }
static string GetTimeZones() { var s = new StringBuilder(); TimeZone t = TimeZone.CurrentTimeZone; s.AppendLine($"Your time zone is {t.GetUtcOffset(DateTime.Now).Hours.ToString()} from UTC (Coordinated Universal Time)."); if (t.IsDaylightSavingTime(DateTime.Now) == false) { s.AppendLine($"You are on Standard Time (ST)."); } else { s.AppendLine($"You are on Daylight Time (DT)."); } return(s.ToString()); }
public static string GetTimeZoneInfo() { TimeZone curTimeZone = TimeZone.CurrentTimeZone; TimeSpan currentOffset = curTimeZone.GetUtcOffset(DateTime.Now); Console.WriteLine("UTC offset:", currentOffset); string offset = "GMT "; if (!currentOffset.ToString().Contains("-")) { offset = offset + "+" + currentOffset.ToString(); } else { offset = offset + currentOffset.ToString(); } return(offset); }
private void WorkOutTime() { Invoke(new Action(() => { // Get DaylightTime object System.Globalization.DaylightTime dl = curTimeZone.GetDaylightChanges(DateTime.Now.Year); // What is GMT (also called Coordinated Universal Time (UTC) DateTime curUTC = curTimeZone.ToUniversalTime(DateTime.Now); // What is GMT/UTC offset ? TimeSpan currentOffset = curTimeZone.GetUtcOffset(DateTime.Now); //---------------------------------------------------------------- lbl_local_tz.Text = TimeZoneInfo.Local.DisplayName; // Difference between standard time and the daylight-saving time. TimeZoneInfo localZone = TimeZoneInfo.Local; string answer = (localZone.BaseUtcOffset >= TimeSpan.Zero) ? "later" : "earlier"; lbl_time_info.Text = "Local time now is " + dl.Delta + " (hh:mm:ss) " + answer + " than UTC."; lbl_UTC.Text = curUTC.ToString(); lbl_local_time.Text = DateTime.Now.ToString(); lbl_utc_offset.Text = currentOffset.ToString(); lbl_DST_setting.Text = curTimeZone.IsDaylightSavingTime(DateTime.Now) ? "On" : "Off"; lbl_dst_start.Text = dl.Start.ToString(); lbl_dst_ends.Text = dl.End.ToString(); lbl_timezone_name.Text = curTimeZone.StandardName; lbl_daylight_name.Text = curTimeZone.DaylightName; //--------------------------------------------------------------------------- DateTime timeUtc = curTimeZone.ToUniversalTime(DateTime.Now); var dt = DateTime.SpecifyKind(timeUtc, DateTimeKind.Utc); //TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); TimeZoneInfo tZone = TimeZoneInfo.FindSystemTimeZoneById(cmbobx_tzones.SelectedItem.ToString()); DateTime TheTime = TimeZoneInfo.ConvertTimeFromUtc(dt, tZone); lbl_time_in_tz.Text = TheTime.ToString(); })); }
private void Form1_Load(object sender, EventArgs e) { TablesDropDownList.SelectedIndex = 1; ClockPossitionDropDownList.SelectedIndex = 0; DateTime currentTime = DateTime.Now; this.radTimePicker1.Value = currentTime; SynchronizeTime(); timer.Start(); try { RegistryKey timeZoneInfoKey = Registry.LocalMachine. OpenSubKey(@"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"); if (timeZoneInfoKey != null) { object timeZoneKeyName = timeZoneInfoKey.GetValue("TimeZoneKeyName"); if (timeZoneKeyName != null) { RegistryKey timeZoneNameKey = Registry.LocalMachine. OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Time Zones\" + timeZoneKeyName); if (timeZoneKeyName != null) { object displayName = timeZoneNameKey.GetValue("Display"); if (displayName != null) { radLabelTimeZone.Text = displayName.ToString(); return; } } } } } catch { } TimeZone localZone = TimeZone.CurrentTimeZone; int hours = localZone.GetUtcOffset(currentTime).Hours; radLabelTimeZone.Text = "UTC" + (hours > 0 ? "+" : "-") + Math.Abs(hours).ToString(); this.radTimePicker1.Value = null; }
private static string GetCurrentTimezoneOffset() { try { // WP8 doesn't support the 'old' way of getting the time zone. #if UNITY_WP8 || UNITY_METRO TimeSpan currentOffset = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now); #else TimeZone localZone = TimeZone.CurrentTimeZone; DateTime currentDate = DateTime.Now; TimeSpan currentOffset = localZone.GetUtcOffset(currentDate); #endif return(String.Format("{0}{1:D2}", currentOffset.Hours >= 0 ? "+" : "", currentOffset.Hours)); } catch (Exception) { return(null); } }
public static SunriseSunset GetSunriseSunset(Location location, LocalDate localDate) { DateTime today = new DateTime(localDate.Year, localDate.Month, localDate.Day); var julianDay = SunriseSunsetUtil.calcJD(today); var sunriseDouble = SunriseSunsetUtil.calcSunRiseUTC(julianDay, location.Latitude, location.Longitude); var sunsetDouble = SunriseSunsetUtil.calcSunSetUTC(julianDay, location.Latitude, location.Longitude); TimeZone localZone = TimeZone.CurrentTimeZone; int utcOffset = localZone.GetUtcOffset(today).Hours; DateTime?sunriseDt = SunriseSunsetUtil.getDateTime(sunriseDouble, utcOffset, today, false); DateTime?sunsetDt = SunriseSunsetUtil.getDateTime(sunsetDouble, utcOffset, today, false); if (sunriseDt == null || sunsetDt == null) { throw new ApplicationException("Could not get sunset time."); } return(new SunriseSunset(ToLocalTime(sunriseDt.Value), ToLocalTime(sunsetDt.Value))); }
/// <summary> Method returns the fractional UTC offset in hours of the /// current timezone. /// </summary> /// <returns>The fractional UTC offset in hours /// </returns> public static double GetUTCOffsetForCurrentTimeZone() { double utcOffset = 0; try { TimeZone localZone = TimeZone.CurrentTimeZone; DateTime baseUTC = new DateTime(); // Calculate the local time and UTC offset. DateTime localTime = localZone.ToLocalTime(baseUTC); TimeSpan localOffset = localZone.GetUtcOffset(localTime); utcOffset = localOffset.TotalHours; } catch (Exception) { // what to do now? } return(utcOffset); }
public static String convertUTCDateToLocal(String sDate, TimeZone timezone) { if (sDate == null || sDate.Length == 0 || isInAllDayFormat(sDate)) return sDate; if (timezone == null) return sDate; if (!sDate.EndsWith("Z")) return sDate; DateTime date = DateTime.ParseExact(sDate, PATTERN_UTC, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); date.Add(timezone.GetUtcOffset(date)); return date.ToString(PATTERN_UTC); }
public static String NormalizeToISO8601(String sDate, TimeZone tz) { if (sDate == null || sDate.Length == 0) return sDate; if (tz != null) { // // Try to apply the timezone // DateTime date; try { date = DateTime.ParseExact(sDate, PATTERN_UTC, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); if (!sDate.EndsWith("000000Z")) { sDate = date.Add(tz.GetUtcOffset(date)).ToString(PATTERN_UTC); } } catch (FormatException) { // // Ignore this error. The date isn't in this format. // // Try with yyyy-MM-dd'T'HH:mm:ss'Z' try { date = DateTime.ParseExact(sDate, PATTERN_UTC_WSEP, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); if (!sDate.EndsWith("00:00:00Z")) { sDate = date.Add(tz.GetUtcOffset(date)).ToString(PATTERN_UTC_WSEP); } } catch (Exception) { // // Ignore this error. The date isn't in this format. // } } } int year = -1; int month = -1; int day = -1; String tmp = null; int last = 0; // // The first four digits are the year // tmp = sDate.Substring(0, 4); year = Int32.Parse(tmp); // // Read the month // char c = sDate[4]; if (c == '/' || c == '-') { tmp = sDate.Substring(5, 2); last = 7; } else { tmp = sDate.Substring(4, 2); last = 6; } month = Int32.Parse(tmp); // // Read the day // c = sDate[last]; if (c == '/' || c == '-') { tmp = sDate.Substring(last + 1, 2); } else { tmp = sDate.Substring(last, 1); } day = Int32.Parse(tmp); StringBuilder isoDate = new StringBuilder(10); isoDate.Append(year); isoDate.Append("-"); if (month < 10) { isoDate.Append("0"); } isoDate.Append(month); isoDate.Append("-"); if (day < 10) { isoDate.Append("0"); } isoDate.Append(day); return isoDate.ToString(); }
public static string convertLocalDateToUTC(string sDate, TimeZone timezone) { if (sDate == null || sDate.Length == 0 || isInAllDayFormat(sDate)) return sDate; if (sDate.IndexOf('Z') != -1) { // // No conversion is required // return sDate; } DateTime date = DateTime.ParseExact(sDate, PATTERN_UTC_WOZ, CultureInfo.InvariantCulture); if (timezone != null) { date.Add(timezone.GetUtcOffset(date)); } //CHECK: this has to be check... return date.ToString(PATTERN_UTC); }