Parse Datetime With Time Zone of Form Pst/Cest/Utc/Etc

Parse DateTime with time zone of form PST/CEST/UTC/etc

AFAIK the time zone abbreviations are not recognized. However if you replace the abbreviation with the time zone offset, it will be OK. E.g.:

DateTime dt1 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+2"), "dd-MMM-yy HH:mm:ss z", culture);
DateTime dt2 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02"), "dd-MMM-yy HH:mm:ss zz", culture);
DateTime dt3 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02:00"), "dd-MMM-yy HH:mm:ss zzz", culture);

Parse DateTime with time zone of form PST/CEST/UTC/etc

AFAIK the time zone abbreviations are not recognized. However if you replace the abbreviation with the time zone offset, it will be OK. E.g.:

DateTime dt1 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+2"), "dd-MMM-yy HH:mm:ss z", culture);
DateTime dt2 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02"), "dd-MMM-yy HH:mm:ss zz", culture);
DateTime dt3 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02:00"), "dd-MMM-yy HH:mm:ss zzz", culture);

C# Manually specify a timezone in DateTime.ParseExact

I believe what you're looking for is TimeZoneInfo.

Using TimeZoneInfo, you can get the information you need from TimeZoneInfo.FindSystemTimeZoneById.

Those Ids are based on the operating system, but as long as all of your containers are on Linux (as an example) you will be able to use that to get a UTC time for storage. You mention that you know what timezone your string is in, so you'll likely need something to convert that to Ids readable by TimeZoneInfo.

Code example taken from TimeZoneInfo.FindSystemTimeZoneById

using System;

public class Example
{
public static void Main()
{
// Get time in local time zone
DateTime thisTime = DateTime.Now;
Console.WriteLine("Time in {0} zone: {1}", TimeZoneInfo.Local.IsDaylightSavingTime(thisTime) ?
TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName, thisTime);
Console.WriteLine(" UTC Time: {0}", TimeZoneInfo.ConvertTimeToUtc(thisTime, TimeZoneInfo.Local));
// Get Tokyo Standard Time zone
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
DateTime tstTime = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, tst);
Console.WriteLine("Time in {0} zone: {1}", tst.IsDaylightSavingTime(tstTime) ?
tst.DaylightName : tst.StandardName, tstTime);
Console.WriteLine(" UTC Time: {0}", TimeZoneInfo.ConvertTimeToUtc(tstTime, tst));
}
}

// The example displays output like the following when run on a system in the
// U.S. Pacific Standard Time zone:
// Time in Pacific Standard Time zone: 12/6/2013 10:57:51 AM
// UTC Time: 12/6/2013 6:57:51 PM
// Time in Tokyo Standard Time zone: 12/7/2013 3:57:51 AM
// UTC Time: 12/6/2013 6:57:51 PM

convert string with utc-datetime to datetime-Ojbect

Assuming that you can have not only (UTC), but (UTC+4), (UTC-5) and alike suffixes, I suggest escaping (UTC and ):

  string stringToFormat = "Fri, 30 Jul 2021 11:57:58 (UTC)";

...

DateTime myDateTime = DateTime.ParseExact(
stringToFormat,
new string[] {
"ddd, d MMM yyyy H:m:s '(UTC)'",
"ddd, d MMM yyyy H:m:s '(UTC'z')'",
},
CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);

Demo:

  DateTime demo(string text) => DateTime.ParseExact(
text,
new string[] {
"ddd, d MMM yyyy H:m:s '(UTC)'",
"ddd, d MMM yyyy H:m:s '(UTC'z')'",
},
CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);

string[] tests = new string[] {
"Fri, 30 Jul 2021 11:57:58 (UTC)",
"Fri, 30 Jul 2021 11:57:58 (UTC-1)",
"Fri, 30 Jul 2021 11:57:58 (UTC+1)",
"Fri, 30 Jul 2021 11:57:58 (UTC-14)",
};

string report = string.Join(Environment.NewLine, tests
.Select(test => $"{test,-40} => {demo(test):dd.MM.yyyy HH:mm:ss}"));

Console.Write(report);

Outcome:

Fri, 30 Jul 2021 11:57:58 (UTC)          => 30.07.2021 11:57:58
Fri, 30 Jul 2021 11:57:58 (UTC-1) => 30.07.2021 12:57:58
Fri, 30 Jul 2021 11:57:58 (UTC+1) => 30.07.2021 10:57:58
Fri, 30 Jul 2021 11:57:58 (UTC-14) => 31.07.2021 01:57:58

How can I parse a datetime string containing GMT in the end as its timezone?

Try this:

DateTime parsed = DateTime.ParseExact("Tue, 03 September 2013 02:05:50 GMT", 
"ddd, dd MMMM yyyy HH:mm:ss Z",
CultureInfo.InvariantCulture);

You should use Z for utc as "GMT". And the 3th of September was on a Tuesday.

How to Parse a Date Time with TimeZone Info

You need to trim the time zone abbreviation off using normal string operations, then specify a custom date and time format string. For example:

// After trimming
string text = "Thu Sep 24 2015 00:00:00 GMT+0530";
var dto = DateTimeOffset.ParseExact(
text,
"ddd MMM d yyyy HH:mm:ss 'GMT'zzz",
CultureInfo.InvariantCulture);
Console.WriteLine(dto);

Note the use of CultureInfo.InvariantCulture here - you almost certainly don't want to parse using the current thread's current culture.

how to parse datetime from this format?

DateTime.Parse() method doesn't recognize your current date time string, so you need to reformat it into one of the formats that this method can understand.
The following snippet could be a bit overkill :-) for this problem but it can handle quite a few scenarios.

//  "20170620 21:22:02 EST" -> "wrong" format
// "2017-06-20T21:22:02 -05:00" -> correct format
String input = "20170620 21:22:02 EST";
String temp = input;

// Handle US time zones.
String[] timeZones = {"AST", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT", "AKST", "AKDT", "HST", "HAST", "HADT", "SST", "SDT", "CHST"};

Int32[] utcOffsets = { -4, -5, -4, -6, -5, -7, -6, -8, -7, -9, -8, -10, -10, -9, -11, -10, 10 };

// Correct the timezone part
for (int i = 0; i < timeZones.Length; i++)
{
String timeZonePattern = @"\b" + timeZones[i] + @"\b";
String timeZoneReplPattern = String.Format("{0}:00", utcOffsets[i].ToString("+00;-00"));

temp = Regex.Replace(input, timeZonePattern, timeZoneReplPattern);
if (temp != input)
{
break;
}
}

// Correct the date part
String datePattern = @"(?<year>[\d]{4})(?<month>[0][1-9]|[1][0-2])(?<day>[0][1-9]|[1-2][0-9]|3[0-1])\s*";
String dateReplPattern = @"${year}-${month}-${day}T";
temp = Regex.Replace(temp, datePattern, dateReplPattern);

// Now we should have a correct date time string
DateTime dt;
try
{
dt = DateTime.Parse(temp);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Hope this can help.

Convert custom DateTime string to DateTime object

hh is for a 12 hour clock. You should use HH for a 24 hour clock. You'll also need to see the mentioned duplicate for better timezone handling.

When in doubt about parsing custom formats, check the documentation! See Custom Date and Time Format Strings on MSDN.



Related Topics



Leave a reply



Submit