using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using gehGassi.Web.Models; namespace gehGassi.Web.Helper { /// /// Hilfsklasse für den Umgang mit Zeitzonen /// public static class TimeZoneHelper { /// /// Gibt eine Liste aller Zeitzonen zurück /// /// Liste public static List GetTimeZones() { var timeZones = new List(); foreach (var zone in TimeZoneInfo.GetSystemTimeZones()) { timeZones.Add(new TimeZoneVm() { Id = zone.Id, Name = zone.DisplayName }); } return timeZones; } /// /// Hilfsmethode die aus einem UTC-Offset als string die erste passende Zeitzone (Basis ohne Daylightsaving) auswählt /// /// Offset /// Id der Zeitzone public static string GetTimezoneIdByOffset(string offset) { offset = offset.Replace("+", ""); var timeSpan = TimeSpan.ParseExact(offset, "hh\\:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None); var firstOrDefault = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(c => c.BaseUtcOffset == timeSpan); if (firstOrDefault != null) return firstOrDefault.Id; return "W. Europe Standard Time"; } /// /// Konvertiert ein UTC-Date in ein Datum das der aktuellen Auswahl des Benutzers entspricht /// /// Datum in UTC-Format welches in das aktuell lokale Datum übersetzt werden soll /// Id der Zeitzone /// Datum in lokaled Datum konvertiert public static DateTime ConvertToLocal(DateTime utcDate, string timeZoneId) { var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); return TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZoneInfo); } /// /// Konvertiert ein Benutzer bezogenes lokales Datum basierend auf der aktuellen Auswahl des Benutzers in ein UTC Datum /// /// Datum welches in UTC konvertiert werden soll /// Id der Zeitzone /// Datum in UTC Konvertiert public static DateTime ConvertToUtc(DateTime localDate, string timeZoneId) { var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); return TimeZoneInfo.ConvertTimeToUtc(localDate, timeZoneInfo); } } }