How can I convert Tue, 01 Nov 2016 02:00 PM EET datetime string to DateTime in C#? What is a good practice to do it?
Use DateTime.TryParseExact with a format string that represents a generic datetime.
If you can have multiple formats then use the DateTime.TryParseExact overload that takes an array of formats.
You can find all the format strings here:
Custom Date and Time Format Strings
For example, "Tue" is represented by "ddd", "Nov" by "MMM" etc.
NOTE: The string formats are case sensitive so while "M" represents the month number, "m" represents the minute number. Getting them mixed up will cause the parse to fail.
By replacing timezone abbreviation with zone offset you can convert using DateTime.ParseExact
string date = "Tue, 01 Nov 2016 02:00 PM EET";
DateTime dt = DateTime.ParseExact(date.Replace("EET", "+2"), "ddd, dd MMM yyyy hh:mm tt z", CultureInfo.InvariantCulture);
and if you want more safer way by checking exception then you can using DateTime.TryParseExact method
Use DateTime.TryParseExact where the format string is built using this table.
Custom date and time formats does not recognize timezone abbrevations. You need to escape them as a string literal delimiter.
var dt = DateTime.ParseExact("Tue, 01 Nov 2016 02:00 PM EET",
"ddd, dd MMM yyyy hh:mm tt 'EET'",
CultureInfo.InvariantCulture);
dt.Dump();
Related
I'm trying to parse DateTime data from podcast XML.
Basically, it comprises http header format.
(Format-A) Fri, 28 Aug 2015 00:00:00 EST
But, sometimes it has the different format with 4 digit days and month like below.
(Format-B) Thur, 30 July 2015 00:00:00 EST
I don't know why the Podcast provides 2 different formats at the same time.
I thought I could simply parse this format as this website mentioned.
https://www.dotnetperls.com/datetime-parse
But it didn't work with just DateTime.Parse() method
So I wrote this code.
try
{
dtPubDate = DateTime.ParseExact(strhttpTime,
"ddd, dd MMM yyyy HH:mm:ss 'EST'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
catch (FormatException)
{
dtPubDate = DateTime.ParseExact(strhttpTime,
"dddd, dd MMMM yyyy HH:mm:ss 'EST'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
As I wrote this code, if the first format doesn't work, try the second one.
But it still got the exception with Format-B.
This URL is what am having the problem with.
http://www.thebreathingmusic.com/podcast/podcast.xml
As you can see, there are 2 different formats with pubDate tag.
What am I missing?
The format string dddd will match against the entire day name, e.g. "Thursday", not 4 characters.
From the docs:
The "dddd" custom format specifier (plus any number of additional "d" specifiers) represents the full name of the day of the week. The localized name of the day of the week is retrieved from the DateTimeFormatInfo.DayNames property of the current or specified culture.
You could just trim everything before the comma and parse that instead.
var tidyDate = strhttpTime.Split(',')[1].Trim();
dtPubDate = DateTime.ParseExact(
tidyDate,
"ddd, dd MMM yyyy HH:mm:ss 'EST'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
How do you parse the default git format to a DateTime in C#?
As per What is the format for --date parameter of git commit
The default date format from git looks like Mon Jul 3 17:18:43 2006 +0200.
Right now I don't have control over the output, this strings comes from another tool that printed the date and I need to parse it.
I wouldn't parse this to DateTime, I would parse it to DateTimeOffset since it has a UTC offset value inside of it.
Why? Because if you parse it to DateTime, you will get a DateTime as Local and it might generate different results for different machines since they can have timezone offsets of that time.
For example, I'm in Istanbul and we use Eastern European Time which use UTC+02:00. If I run the example of your code with ParseExact method, I will get the 07/03/2006 18:18:43 as a Local time.
Why? Because in 3 July 2006, my timezone was in a daylight saving time which is UTC+03:00. That's why it generates 1 hour forwarded result. That's the part makes it ambiguous when you parse it to DateTime.
string s = "Mon Jul 3 17:18:43 2006 +0200";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM d HH:mm:ss yyyy K",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
Now, you have a DateTimeOffset as 07/03/2006 17:18:43 +02:00. You can still get the DateTime part with it's .DateTime property but it's Kind will be Unspecified in that case.
But of course, I suggest to use Noda Time instead which can solve most of the DateTime weirdness.
So far the best format string I found is ddd MMM d HH:mm:ss yyyy K.
DateTime date;
DateTime.TryParseExact(
gitDateString,
"ddd MMM d HH:mm:ss yyyy K",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date
);
This is a very strange date fromat I have never seen before coming back from some API in JSON.
"Tue Aug 04 2015 00:17:38 GMT+0000 (UTC)"
That is generating the following error:
System.FormatException: String was not recognized as a valid DateTime.
Which is understandable when using the following method to parse:
DateTime.Parse(x.process_date.Value)
Anyone dealt with complex date formats that may know how to parse that?
You can use the DateTime.ParseExact method (or DateTime.TryParseExact, to cleanly handle parsing failures) to accomplish this. These methods allow you to explicitly specify the format string.
Something like this could work:
var dateString = "Tue Aug 04 2015 00:17:38 GMT+0000 (UTC)";
var format = "ddd MMM dd yyyy HH:mm:ss GMT+0000 (UTC)";
var parsed = DateTime.ParseExact(
dateString,
format,
System.Globalization.CultureInfo.InvariantCulture);
Or, using TryParseExact:
DateTime parsed;
if (DateTime.TryParseExact(
dateString,
format,
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsed)
{
// parsing was successful
}
else
{
// parsing failed
}
Here's a breakdown of the format string used here:
ddd - The abbreviated name of the day of the week.
MMM - The abbreviated name of the month.
dd - The day of the month, from 01 through 31.
yyyy - The year as a four-digit number.
HH:mm:ss - The hour, using a 24-hour clock from 00 to 23; the minute, from 00 through 59; and the second, from 0 through 59 (delimited by : characters).
GMT+0000 (UTC) - just static text that the format string assumes will always be present. This is pretty brittle and could cause your parsing to fail if the API ever returns different text here. Consider truncating this text, or using NodaTime which offers great support for time zones.
You might need to tweak this format string slightly to your usage -- for example, it wasn't clear from your question whether or not you are using a 12-hour clock or a 24-hour clock.
For more information on how to build a format string, see Custom Date and Time Format Strings on MSDN.
Alternatively, you could eschew using System.DateTime in favor of NodaTime. I'm less familiar with NodaTime myself, but great documentation is available both here on StackOverflow and on NodaTime's site.
I need to format a date in RFC format for an RSS feed. I have tried taking my date and adding the following:
.ToString("ddd, dd mm yyyy HH:mm:ss zzz")
However it seems this is not valid. Any help would be great! The end result I need is, for example, Mon, 01 Jan 2013 GMT
Your question is a bit confusing because your example lacks any time (but has a time-zone).
Nevertheless, try using MMM for month:
.ToString("ddd, dd MMM yyyy HH:mm:ss zzz")
If you don't want time, simply omit that section from the string:
.ToString("ddd, dd MMM yyyy")
But since you mentioned you're generating a string for an RSS feed, you could just use the "R" format specifier to generate a RFC1123-format date / time string:
.ToString("R")
I have a string "11 Jan 2011" which I want to convert to the datatype date (i.e 11 Jan 2011).
I have tried all resources about datetime.parse, datetime.parse exact but all these things gives me the same output 2011/01/11 12:00:00 AM. I really don't understand this behaviour. I tried the following:
1.DateTime date = DateTime.Parse("11 Jan 2011");
2.DateTime date = DateTime.ParseExact("11 Jan 2011" , #"dd MMM yyyy", System.Globalization.CultureInfo.InvariantCulture);
parsing and displaying are not the same thing
you parse the original string to a DateTime object but display results using Date/Time format strings
Both your calls are correct.
A DateTime structure preserves no information about formatting; it just represents the raw date and time.
What you need to do is ensure that when you display your date, you do so in the correct format - e.g. by calling string displayString = date.ToString("dd MMM yyyy");