convert string with utc-datetime to datetime-Ojbect - c#

First of all I am new in C#.
I have to convert a string like
"Fri, 30 Jul 2021 11:57:58 (UTC)"
into a DateTime. I've tried serveral format strings (like "ddd, dd MMM yyyy HH:mm:ss", "r", "R"). But I always get the error message
String was not recognized as a valid DateTime.
Here is my last code for this:
CultureInfo enUS = new CultureInfo("en-US");
string timeStampFormat = "ddd, dd MMM yyyy HH:mm:ss";
DateTime myDateTime;
myDateTime = DateTime.ParseExact(
stringToFormat,
timeStampFormat,
enUS,
DateTimeStyles.AssumeUniversal);
Thanks for your support.
Best regards
Andreas## Heading ##

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

It is the (UTC) which is causing the string to not be recognized as a timestamp. You could account for the (UTC) by removing it, I have provided one method to accomplish this here.
string stringToFormat = "Fri, 30 Jul 2021 11:57:58 (UTC)";
string[] SubString = stringToFormat.Split('(');
stringToFormat = SubString[0].Trim();
string timeStampFormat = "ddd, dd MMM yyyy HH:mm:ss";
DateTime mydateTime = DateTime.ParseExact(stringToFormat, timeStampFormat, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AssumeUniversal);
Or replace the (UTC) with the offset from UTC, which in this case would be 0, and add (z) to timeStampFormat.
string stringToFormat = "Fri, 30 Jul 2021 11:57:58 (UTC)";
stringToFormat = stringToFormat.Replace("(UTC)", "(-0)");
string timeStampFormat = "ddd, dd MMM yyyy HH:mm:ss (z)";
DateTime mydateTime = DateTime.ParseExact(stringToFormat, timeStampFormat, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AssumeUniversal);
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

Related

Unable to parse abbreviated day name from string

I'm trying to parse a date in my string using DateTime.TryParseExact. The string looks like this:
Wed, 21 Apr 2019 07:28:45 GMT
However, the parse function always fails when I use the ddd format specifier. If I remove 'Wed' from the string and the 'ddd' part from the format string, it parses just fine.
Here's a bit of code that reproduces the problem
var ci = CultureInfo.CreateSpecificCulture("en-GB");
var datesToParse = new[] { "Wed, 21 Apr 2019 07:28:45 GMT", "21 Apr 2019 07:28:45 GMT" };
var formats = new[] { "ddd, dd MMM yyyy HH:mm:ss 'GMT'", "dd MMM yyyy HH:mm:ss 'GMT'" };
foreach (var dateToParse in datesToParse)
{
var result = DateTime.TryParseExact(dateToParse, formats, ci, DateTimeStyles.AllowWhiteSpaces, out DateTime parsedDate)
? parsedDate.ToLongDateString()
: $"Unable to parse date: {dateToParse}";
Console.WriteLine(result);
}
Console.ReadLine();
And the output:
Unable to parse date: Wed, 21 Apr 2019 07:28:45 GMT
21 April 2019
I'm not really sure what I'm doing wrong here. Any help would be appreciated.
edit: improved the output and program syntax
Your issue is that 21 April 2019 was a Sunday and not a Wednesday. This works fine "Sun, 21 Apr 2019 07:28:45 GMT"

Convert String with GMT foramt to Datetime

How to convert "Fri Jul 11 2014 01:30:00 GMT-0700 (Pacific Daylight Time)" to Datetime
with the format of "dd/MM/yyyy HH:mm:ss" in C#?
String inputString="Fri Jul 11 2014 01:30:00 GMT-0700 (Pacific Daylight Time)";
// we have no need of the parenthetical, get rid of it
inputString = Regex.Replace(inputString, " \\(.*\\)$", "");
// exact string format ... 'GMT' is literal
DateTime theDate = DateTime.ParseExact(inputString,"ddd MMM dd yyyy HH:mm:ss 'GMT'zzz",
System.Globalization.CultureInfo.InvariantCulture);

How to parse CET/CEST datetime?

I got a JSON on the server, and I try to parse it. The problem is that some dates looks like:
Tue, 03 Sep 2013 12:18:45 CEST
some as:
Sat, 17 Nov 2012 15:39:43 CET
so if I do somethins like:
var processedData = DateTime.ParseExact((string)item.pubDate, "ddd, dd MMM yyyy HH:mm:ss CEST", CultureInfo.InvariantCulture);
only on CEST dates it works, else it raises an exception.
How can I solve it? I hope .Replace() it is not the answer...
You can use Multiple Formats like:
string[] formats = new[]
{
"ddd, dd MMM yyyy HH:mm:ss CEST",
"ddd, dd MMM yyyy HH:mm:ss CET"
};
var processedData = DateTime.ParseExact((string)item.pubDate,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);

C# to Convert String to DateTime

How to convert the below string to DateTime in C#?
Mon Apr 22 07:56:21 +0000 2013
When i tried the code with
Convert.ToDateTime("Mon Apr 22 07:56:21 +0000 2013")
it is throwing error as
String was not considered as valid DateTime
Try DateTime.ParseExact instead.
Example:
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
More examples are available at http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
You have to specify that your input string is in a particular format. Please refer this link and this one too.
Use DateTime.ParseExact like:
string str = "Mon Apr 22 07:56:21 +0000 2013";
DateTime dt = DateTime.ParseExact(str,
"ddd MMM d HH:mm:ss +0000 yyyy",
CultureInfo.InvariantCulture);
You have basically two options for this.
DateTime.Parse() and DateTime.ParseExact(). like
DateTime parseexactdt = DateTime.ParseExact("Mon Apr 22 07:56:21 +0000 2013",
"ddd MMM d HH:mm:ss +0000 yyyy",
CultureInfo.InvariantCulture);
string input = "Mon Apr 22 07:56:21 +0000 2013";
string format = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime dt;
if(DateTime.TryParseExact(input,format, CultureInfo.InvariantCulture,
DateTimeStyles.None,out dt))
{
// do something with dt
}
You can use this:
using System;
using System.Globalization;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
CultureInfo cult = CultureInfo.InvariantCulture;
string txt = "Mon Apr 22 07:56:21 +0000 2013";
string format = "ddd MMM dd hh:mm:ss zzz yyyy";
DateTime dt = DateTime.ParseExact(txt, format, cult);
}
}
}
If you run program from country with +06:00, you get time 13:56:21 with same date

How to parse utc date

How do I Parse Date like
Sat Aug22 14.00:00 UTC +200 2009
I tried using
DateTime.ParseExact("Sat Aug 22 14.00:00 UTC +200 2009", "ddd MMM d HH:mm:ss UTC yyyy", null);
Try this, it works. After 14, you have "." - change it to ":"
DateTime.ParseExact("Sat Aug 22 14:00:00 UTC+0200 2009",
"ddd MMM d HH:mm:ss UTCzzzz yyyy", null);
Reference

Categories

Resources