public static bool ParseProperty(Type type, string value, [NotNullWhen(returnValue: true)] out object?parsedValue) { if (type == typeof(DateTime) || type == typeof(DateTime?)) { parsedValue = DateTime.Parse(value); return(true); } if (type == typeof(ZonedDateTime) || type == typeof(ZonedDateTime?)) { parsedValue = LocalDateTimePattern.CreateWithInvariantCulture(DATETIME_PATTERN).Parse(value).GetValueOrThrow().InUtc(); return(true); } if (type == typeof(LocalDateTime) || type == typeof(LocalDateTime?)) { parsedValue = LocalDateTimePattern.CreateWithInvariantCulture(DATETIME_PATTERN).Parse(value).GetValueOrThrow(); return(true); } if (type == typeof(LocalDate) || type == typeof(LocalDate?)) { parsedValue = LocalDatePattern.CreateWithInvariantCulture(DATE_PATTERN).Parse(value).GetValueOrThrow(); return(true); } if (type == typeof(LocalTime) || type == typeof(LocalTime?)) { parsedValue = LocalTimePattern.CreateWithInvariantCulture(TIME_PATTERN).Parse(value).GetValueOrThrow(); return(true); } parsedValue = null; return(false); }
public static RaidTime Parse(string value) { foreach (string format in Formats) { var parse = LocalDateTimePattern.CreateWithInvariantCulture(format).Parse(value); if (!parse.Success) { continue; } var localDt = new LocalDateTime(DateTimeOffset.Now.Year, parse.Value.Month, parse.Value.Day, parse.Value.Hour, parse.Value.Minute); var nowLocalDt = new LocalDateTime(DateTimeOffset.Now.Year, DateTimeOffset.Now.Month, DateTimeOffset.Now.Day, DateTimeOffset.Now.Hour, DateTimeOffset.Now.Minute); if (localDt.CompareTo(nowLocalDt) <= 0) { localDt = localDt.PlusYears(1); } int offset = -8; if (TimeZoneInfo.Local.IsDaylightSavingTime(localDt.ToDateTimeUnspecified())) { offset = -7; } var offsetDt = new OffsetDateTime(localDt, Offset.FromHours(offset)); return(new RaidTime(offsetDt)); } throw new FormatException("Couldn't parse value to any format"); }
/// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var pattern = LocalDateTimePattern.CreateWithInvariantCulture("r-MM-ddTHH:mm:ss LOC"); var utc = new LocalDateTime(new LocalInstant(Ticks)); return(pattern.Format(utc)); }
private static IHostBuilder CreateHostBuilder(string[] args) => Host .CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.Configure <OctopusConfiguration>(context.Configuration.GetSection("Octopus")); services.Configure <InfluxDbService.Config>(context.Configuration.GetSection("Influx")); services.Configure <JsonSerializerOptions>(options => { options.WriteIndented = false; options.Converters.Add(new NodaPatternConverter <LocalDateTime>( LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss"))); options.Converters.Add(new NodaPatternConverter <OffsetDateTime>( OffsetDateTimePattern.GeneralIso)); options.Converters.Add(new NodaPatternConverter <Instant>(InstantPattern.General)); options.PropertyNameCaseInsensitive = true; }); services.AddSingleton <InfluxDbService>(); services.AddHttpClient <OctopusService>(); services.AddSingleton <OctopusStoreService>(); services.AddHostedService <OctopusTariffService>(); services.AddHostedService <OctopusConsumptionService>(); services.AddHostedService <OctopusPriceService>(); }) .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration) .Enrich.FromLogContext() .WriteTo.Console() );
public List <Attendance> GetAttendances() { JArray arr = JObject.Parse(Request("/Attendances"))["Attendances"].ToObject <JArray>(); List <Attendance> Attendances = new List <Attendance>(); try { for (int i = 0; i < arr.Count; i++) { JObject attendanceObject = arr[i].ToObject <JObject>(); string id = attendanceObject.GetValue("Id").ToString(); string lessonId = attendanceObject.SelectToken("Lesson").ToObject <JObject>().GetValue("Id").ToString(); // trip LocalDate date = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(attendanceObject.GetValue("Date").ToString()).Value; LocalDateTime addDate = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(attendanceObject.GetValue("AddDate").ToString()).Value; int lessonNumber = int.Parse(attendanceObject.GetValue("LessonNo").ToString()); int semesterNumber = int.Parse(attendanceObject.GetValue("Semester").ToString()); string typeId = attendanceObject.SelectToken("Type").ToObject <JObject>().GetValue("Id").ToString(); string authorId = attendanceObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString(); Attendance attendance = new Attendance(id, lessonId, date, addDate, lessonNumber, semesterNumber, typeId, authorId); Attendances.Add(attendance); } attendances = Attendances; return(Attendances); } catch (Exception ex) { Log("failed to parse response (attendances)"); Log(ex.Message); throw ex; } }
public List <Event> GetEvents() { JArray arr = JObject.Parse(Request("/HomeWorks"))["HomeWorks"].ToObject <JArray>(); List <Event> Events = new List <Event>(); try { for (int i = 0; i < arr.Count; i++) { JObject eventObject = arr[i].ToObject <JObject>(); string id = eventObject.GetValue("Id").ToString(); string description = eventObject.GetValue("Content").ToString(); LocalDate date = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(eventObject.GetValue("Date").ToString()).Value; string eventCategoryId = eventObject.SelectToken("Category").ToObject <JObject>().GetValue("Id").ToString(); int lessonNumber = int.Parse(eventObject.GetValue("LessonNo").ToString()); string authorId = eventObject.SelectToken("CreatedBy").ToObject <JObject>().GetValue("Id").ToString(); LocalDateTime addDate = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(eventObject.GetValue("AddDate").ToString()).Value; Event e = new Event(id, description, date, eventCategoryId, lessonNumber, authorId, addDate); Events.Add(e); } this.events = Events; return(Events); } catch (Exception ex) { Log("failed to parse response (events)"); Log(ex.Message); throw ex; } }
public static ZonedDateTime ParseToZonedDateTime(this string stringTimestamp, string format, string ianaTimeZone) { var pattern = LocalDateTimePattern.CreateWithInvariantCulture(format); var localDateTime = pattern.Parse(stringTimestamp).Value; return(localDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb[ianaTimeZone])); }
/// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var date = new LocalDate(duration.FloorDays); var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-ddTHH:mm:ss LOC"); var utc = new LocalDateTime(date, LocalTime.FromNanosecondsSinceMidnight(duration.NanosecondOfFloorDay)); return(pattern.Format(utc)); }
/// <summary> /// Check if a date and time string format is correct. /// </summary> /// <param name="date">Local date string "2020-12-31"</param> /// <param name="time">Local time string "12:12 AM"</param> public static bool DateTimeFormatIsCorrect(string date, string time = "00:00") { var result = LocalDateTimePattern .CreateWithInvariantCulture( $"{year_month_date} {hour_minute}") .Parse(date + " " + time); return(result.Success); }
static void Main() { string s = "2014-02-02T24:00:00"; var pattern = LocalDateTimePattern.CreateWithInvariantCulture ("yyyy-MM-dd'T'HH:mm:ss"); var dt = pattern.Parse(s).Value; Console.WriteLine(pattern.Format(dt)); // 2014-02-03T00:00:00 }
static void Main() { string text = "2007-04-05T24:00"; var pattern = LocalDateTimePattern.CreateWithInvariantCulture ("yyyy-MM-dd'T'HH:mm"); var dateTime = pattern.Parse(text).Value; Console.WriteLine(pattern.Format(dateTime)); // 2007-04-06T00:00 }
/// <summary> /// Convert from yyyy-mm-dd to dd-mm-yyyy /// </summary> /// <param name="local_date">ISO date</param> /// <returns>EU date format</returns> public string ConvertToEUDate(string local_date) { var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd"); var date = pattern.Parse(local_date).Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); logger.Info("converted datetime: " + local_date); return(date); }
static DateTimeOffset LocalTimeToUtc(string localDate) { var pattern = LocalDateTimePattern.CreateWithInvariantCulture("dd/MM/yyyy"); LocalDateTime ldt = pattern.Parse(localDate).Value; ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb["Australia/Sydney"]); Instant instant = zdt.ToInstant(); ZonedDateTime utc = instant.InUtc(); return(utc.ToDateTimeOffset()); }
public static DateTime EstDateTimeToUtc(string dateTime) { var tz = DateTimeZoneProviders.Tzdb["America/New_York"]; const string format = "MM/dd/yyyy HH:mm"; var pattern = LocalDateTimePattern.CreateWithInvariantCulture(format); var dt = pattern.Parse(dateTime).Value; return(tz.AtLeniently(dt).ToDateTimeOffset().DateTime); }
static void Main() { var text = "Feb 5, 2016 7:45 PM"; var zone = DateTimeZoneProviders.Tzdb["Europe/Istanbul"]; var pattern = LocalDateTimePattern.CreateWithInvariantCulture("MMM d, YYYY h:mm tt"); var local = pattern.Parse(text).Value; var zoned = local.InZoneStrictly(zone); var utc = zoned.WithZone(DateTimeZone.Utc); Console.WriteLine(utc); // 2016-02-05T17:45:00 UTC (+00) }
public static void Main() { string _QsDateTime = "12.11.2016 21:30"; var _CountryZone = DateTimeZoneProviders.Tzdb["Europe/Istanbul"]; var _DatePattern = LocalDateTimePattern.CreateWithCurrentCulture("dd.MM.yyyy HH:mm"); var _LocalTime = _DatePattern.Parse(_QsDateTime).Value; var _LocalTime2TargetZoneTime = _LocalTime.InZoneStrictly(_CountryZone); var _TargetZone2Utc = _LocalTime2TargetZoneTime.WithZone(DateTimeZone.Utc).ToDateTimeUtc(); _QsDateTime = _TargetZone2Utc.ToString("yyyy-MM-dd HH:mm:ss"); Console.WriteLine(_QsDateTime); }
private bool TryGetLocalPattern(string format, out IPattern <LocalDateTime> pattern) { pattern = default; try { pattern = LocalDateTimePattern.CreateWithInvariantCulture(format); } catch { return(false); } return(true); }
public void ChicagoChristmas() { const string dateTime = "2017-12-25 20:30:40"; const string timeZone = "America/Chicago"; var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss"); var ldt = pattern.Parse(dateTime).Value; var zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]); var date = zdt.ToDateTimeOffset(); date.ShouldBeEquivalentTo(new DateTimeOffset(2017, 12, 25, 20, 30, 40, TimeSpan.FromHours(-6))); Console.WriteLine(date.ToString("s")); }
protected CsvReaderBase(Context context) : base(context) { InstantPattern = HasZoneInfo ? null : string.IsNullOrWhiteSpace(Context.CsvDateTimeFormat) ? InstantPattern.ExtendedIso : InstantPattern.CreateWithInvariantCulture(Context.CsvDateTimeFormat); LocalDateTimePattern = HasZoneInfo ? string.IsNullOrWhiteSpace(Context.CsvDateTimeFormat) ? LocalDateTimePattern.ExtendedIso : LocalDateTimePattern.CreateWithInvariantCulture(Context.CsvDateTimeFormat) : null; var isTimeFormatUtc = (InstantPattern?.PatternText.Contains("'Z'") ?? false) || (LocalDateTimePattern?.PatternText.Contains("'Z'") ?? false); if (Context.CsvDateOnlyField != null) { isTimeFormatUtc |= Context.CsvDateOnlyFormat.Contains("Z"); } if (!isTimeFormatUtc) { return; } DefaultBias = Duration.Zero; if (!HasZoneInfo) { return; } var patterns = new[] { InstantPattern?.PatternText, LocalDateTimePattern?.PatternText, Context.CsvDateOnlyFormat } .Where(s => !string.IsNullOrWhiteSpace(s)) .ToList(); var settingMessage = Context.Timezone != null ? $"/{nameof(context.Timezone)}='{context.Timezone}'" : $"/{nameof(context.CsvTimezoneField)}={context.CsvTimezoneField}"; Log.Warn($"Ignoring the {settingMessage} value since the time-format patterns \"{string.Join("\" and \"", patterns)}\" contain zone-info."); Context.Timezone = null; Context.CsvTimezoneField = null; }
// Helper method to make it slightly easier for tests to skip "bad" cultures. private LocalDateTimePattern CreatePatternOrNull(string patternText, CultureInfo culture, LocalDateTime templateValue) { try { return(LocalDateTimePattern.Create(patternText, culture)); } catch (InvalidPatternException) { // The Malta long date/time pattern in Mono 3.0 is invalid (not just wrong; invalid due to the wrong number of quotes). // Skip it :( // See https://bugzilla.xamarin.com/show_bug.cgi?id=11363 return(null); } }
public void CreateWithCurrentCulture() { var dateTime = new LocalDateTime(2017, 8, 23, 12, 34, 56); using (CultureSaver.SetCultures(Cultures.FrFr)) { var pattern = LocalDateTimePattern.CreateWithCurrentCulture("g"); Assert.AreEqual("23/08/2017 12:34", pattern.Format(dateTime)); } using (CultureSaver.SetCultures(Cultures.FrCa)) { var pattern = LocalDateTimePattern.CreateWithCurrentCulture("g"); Assert.AreEqual("2017-08-23 12:34", pattern.Format(dateTime)); } }
public void IsoPattern(string text) { // We assert that the text round-trips. If it does, it's // reasonable to assume it parsed correctly... var shortPattern = LocalDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm"); var pattern = new CompositePatternBuilder <LocalDateTime> { { LocalDateTimePattern.ExtendedIso, _ => true }, { shortPattern, ldt => ldt.Second == 0 && ldt.NanosecondOfSecond == 0 } }.Build(); var value = pattern.Parse(text).Value; string formatted = pattern.Format(value); Assert.AreEqual(text, formatted); }
public List <Grade> GetGrades() { JArray arr = JObject.Parse(Request("/Grades"))["Grades"].ToObject <JArray>(); List <Grade> Grades = new List <Grade>(); try { for (int i = 0; i < arr.Count; i++) { JObject gradeObject = arr[i].ToObject <JObject>(); string id = gradeObject.GetValue("Id").ToString(); string lessonId = gradeObject.SelectToken("Lesson").ToObject <JObject>().GetValue("Id").ToString(); string subjectId = gradeObject.SelectToken("Subject").ToObject <JObject>().GetValue("Id").ToString(); string categoryId = gradeObject.SelectToken("Category").ToObject <JObject>().GetValue("Id").ToString(); string authorId = gradeObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString(); string grade = gradeObject.GetValue("Grade").ToString(); LocalDate date = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(gradeObject.GetValue("Date").ToString()).Value; LocalDateTime addDate = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(gradeObject.GetValue("AddDate").ToString()).Value; int semesterNumber = int.Parse(gradeObject.GetValue("Semester").ToString()); bool isConstituent = bool.Parse(gradeObject.GetValue("IsConstituent").ToString()); bool isSemesterGrade = bool.Parse(gradeObject.GetValue("IsSemester").ToString()); bool isSemesterProposition = bool.Parse(gradeObject.GetValue("IsSemesterProposition").ToString()); bool isFinalGrade = bool.Parse(gradeObject.GetValue("IsFinal").ToString()); bool isFinalProposition = bool.Parse(gradeObject.GetValue("IsFinalProposition").ToString()); string gradeCommentId; if (gradeObject.Property("Comments") != null) { gradeCommentId = gradeObject.SelectToken("Comments").ToObject <JArray>()[0].ToObject <JObject>().GetValue("Id").ToString(); } else { gradeCommentId = String.Empty; } Grade g = new Grade(id, lessonId, subjectId, categoryId, authorId, grade, date, addDate, semesterNumber, isConstituent, isSemesterGrade, isSemesterProposition, isFinalGrade, isFinalProposition, gradeCommentId); Grades.Add(g); } grades = Grades; return(Grades); } catch (Exception ex) { Log("failed to parse response (grades)"); Log(ex.Message); throw ex; } }
public DateTimeFormatSpecification(string format) { if (format == null) { throw new ArgumentNullException(nameof(format)); } _hasOffset = TimeFormatSpecification.HasOffset(format); if (_hasOffset) { _offsetPattern = OffsetDateTimePattern.CreateWithInvariantCulture(TimeFormatSpecification.GetNodaTimePattern(format)); } else { _localPattern = LocalDateTimePattern.CreateWithInvariantCulture(TimeFormatSpecification.GetNodaTimePattern(format)); } }
/// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if (this == BeforeMinValue) { return(InstantPatternParser.BeforeMinValueText); } if (this == AfterMaxValue) { return(InstantPatternParser.AfterMaxValueText); } var date = new LocalDate(duration.FloorDays); var pattern = LocalDateTimePattern.CreateWithInvariantCulture("uuuu-MM-ddTHH:mm:ss.FFFFFFFFF 'LOC'"); var utc = new LocalDateTime(date, LocalTime.FromNanosecondsSinceMidnight(duration.NanosecondOfFloorDay)); return(pattern.Format(utc)); }
/// <summary> /// Create a UTC DateTime from given date and time strings and the time zone /// </summary> /// <param name="date">Local date string "2020-12-31"</param> /// <param name="time">Local time string "12:12 AM"</param> /// <param name="timeZone">The time zone of the local date/time</param> public static DateTime ToUTC(string date, string time = "00:00", string timeZone = default_timezone) { var result = LocalDateTimePattern .CreateWithInvariantCulture( $"{year_month_date} {hour_minute}") .Parse(date + " " + time); if (!result.Success) { throw new InvalidPatternException(result.Exception.Message); } return(result.Value .InZoneStrictly(DateTimeZoneProviders.Tzdb[timeZone]) .ToDateTimeUtc()); }
static void Main(string[] args) { //This is an attempt to make a birthday checker //User will enter DOB, program will compare that to current day //If the DOB indicates the person is 21 or, program will display VALID SALE //This is a test of concept //I just want to see if I can do it Console.Write("Enter DOB: "); string input = Console.ReadLine(); //get input LocalDateTimePattern pattern = LocalDateTimePattern.CreateWithInvariantCulture("MMddyy"); //set pattern for parsing from string ParseResult <LocalDateTime> parseResult = pattern.Parse(input); //parse string from input LocalDateTime dob = parseResult.Value; //returns value of parse result //date of birth set as variable 'dob' Instant today = SystemClock.Instance.Now; //gets current date from system clock var timeZone = DateTimeZoneProviders.Tzdb["US/Central"]; //gets US Central as Time zone ZonedDateTime zonedToday = today.InZone(timeZone); //converts instant variable to ZonedDateTime in Central Time LocalDateTime localToday = zonedToday.LocalDateTime; //Converts ZonedDateTime to LocalDateTime, suitable for Period //final, useable value for today set as variable 'localToday' Period agePeriod = Period.Between(dob, localToday); //gets amount of time between two dates long age = agePeriod.Years; //gets years component of period. Component Years takes long data type //this is the variable to use for age. We don't care about months, weeks, days, etc //Only LocalDateTime variables can use Period. Instant variable must be converted to LocalDateTime via ZonedDateTime if (age >= 21) //simple conditional. Does the date of birth put the person at or over 21 years old { Console.WriteLine($"VALID SALE ({age})"); } else { Console.WriteLine($"DENY SALE({age})"); } //I can do it }
public void FortWayneChristmas() { const string dateTime = "2017-12-25 20:30:40"; var timeZone = TimeZoneLookup.GetTimeZone(40.977506, -85.196059).Result; timeZone.Should().Be("America/Indiana/Indianapolis"); var abbreviation = TZNames.GetAbbreviationsForTimeZone(timeZone, "en-US").Generic; abbreviation.Should().Be("ET"); var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss"); var ldt = pattern.Parse(dateTime).Value; var zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]); var date = zdt.ToDateTimeOffset(); date.ShouldBeEquivalentTo(new DateTimeOffset(2017, 12, 25, 20, 30, 40, TimeSpan.FromHours(-5))); Console.WriteLine(date.ToString("s")); }
/// <returns> a time series from Apple Inc. ticks.</returns> public static TimeSeries LoadAppleIncSeries() { var assembly = Assembly.GetExecutingAssembly(); var resourceName = @"TA4N.Example.Resources.appleinc_ticks_from_20130101_usd.csv"; List <dynamic> lines = null; var ticks = new List <Tick>(); using (var stream = assembly.GetManifestResourceStream(resourceName)) { if (stream != null) { using (var reader = new StreamReader(stream)) { // Reading all lines of the CSV file var csvReader = new CsvReader(reader); lines = csvReader.GetRecords <dynamic>().ToList(); } } } if (lines != null) { foreach (var line in lines) { var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd"); //Console.WriteLine("Expecting input {0}.", pattern.Format(new LocalDate(2014, 5, 26))); ParseResult <LocalDateTime> parseResult = pattern.Parse(line.date); var date = parseResult.GetValueOrThrow(); double open = double.Parse(line.open); double high = double.Parse(line.high); double low = double.Parse(line.low); double close = double.Parse(line.close); double volume = double.Parse(line.volume); ticks.Add(new Tick(date, open, high, low, close, volume)); } } return(new TimeSeries("apple_ticks", ticks)); }
static void Main(string[] args) { // Main variables/ values to be used var sourceDateTimeString = "08/12/2018 17:37:32.525+02:00"; var sourceDateTimeFormat = "MM/dd/yyyy HH:mm:ss.fffzzz"; var sourceTimeZonePattern = "Africa/Cairo"; //var offset = DateTimeOffset.ParseExact(sourceDateTimeString, sourceDateTimeFormat, Culturei) //TimeZoneInfo testInfo = TimeZoneInfo.Utc; //var offsetFromUtc = testInfo.GetUtcOffset(Convert.ToDateTime(sourceDateTimeString)); var convertedStringDateTime = DateTimeOffset.Parse(sourceDateTimeString, CultureInfo.GetCultureInfo("en-US")).UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss"); //var offsetFromString = convertedDateTime.ToUniversalTime(); var sourceDateTimeAsIsString = DateTimeOffset.Parse(sourceDateTimeString).DateTime.ToString("yyyy-MM-ddTHH:mm:ss"); var targetTimeZone = "UTC"; var targetDateTimeFormat = "yyyy-MM-ddTHH:mm:ss"; //Check if time zone provided separately and that in the DateTimeString match var SourceDateTimePattern = LocalDateTimePattern.CreateWithInvariantCulture(sourceDateTimeFormat); var SourceDateTime = SourceDateTimePattern.Parse(sourceDateTimeAsIsString).Value; var TargetTimeZone = string.IsNullOrEmpty(targetTimeZone) ? sourceTimeZonePattern : targetTimeZone; var sourceTz = DateTimeZoneProviders.Tzdb[sourceTimeZonePattern]; var targetTz = DateTimeZoneProviders.Tzdb[TargetTimeZone]; var SourceZonedDateTime = SourceDateTime.InZoneLeniently(sourceTz); var TargetZonedDateTime = SourceZonedDateTime.WithZone(targetTz); var outPattern = ZonedDateTimePattern.CreateWithInvariantCulture(targetDateTimeFormat, DateTimeZoneProviders.Tzdb); var outputString = outPattern.Format(TargetZonedDateTime); Console.WriteLine(outPattern.Format(TargetZonedDateTime)); }