I hate to ask dumb questions but I've been through the MSDN article a couple times and trying stuff for an hour but no matter what I try I can't get this format to work. Here's what I'm trying to parse:
Thu, Jun 22
With
bool parsed = DateTime.TryParseExact("Thu, Jun 22", #"ddd, MMM dd", CultureInfo.Invariant, DateTimeStyles.None, out dateAndTime);
Using the format:
ddd, MMM dd
Removing the ddd, works so I'm pretty certain there's something with the first part, but I'm not sure what. I've tried using ' ' around the comma and escaping it with backslash, with no luck.
Since "Thu Jun 22" doesn't contain a year, the system will automatically infer the current year, so it will be treated as Thu Jun 22 2016.
Unfortunately, June 22, 2016 is not a Thursday, but actually a Friday. So you should get a FormatException with that value.
Try adding a year or removing the weekday.
Related
From third party I'm getting this string that I'd like to convert to DateTime:
"13 NOV 2018 16:08:52:000:000:000"
I've tried those options but FormatException thrown:
System.DateTime.ParseExact("12 NOV 2018 16:08:52:000:000:000",
"dd MMM yyyy HH:mm:ss:fff:ffffff:fffffffff",
CultureInfo.InvariantCulture)
And the same exception when I've used this:
System.DateTime.ParseExact("12 NOV 2018 16:08:52:000:000:000",
"dd MMM yyyy HH:mm:ss:fff", CultureInfo.InvariantCulture)
Is there a clean way to parse it as is or, I need to use a dirty way such string.Split(new []{':'})?
Note:
For my business needs, I don't need the part of micro/nano seconds.
since this parsing operation occurs many times in a second, the efficiency is a key factor.
Update
I chose the #Tim's suggestion to do string manipulation:
string date = "12 NOV 2018 16:08:52:000:000:000";
date = date.Remove(date.Remove(date.LastIndexOf(':')).LastIndexOf(':'));
DateTime result = System.DateTime.ParseExact(date, "dd MMM yyyy HH:mm:ss:fff", System.Globalization.CultureInfo.InvariantCulture);
The reasons:
I can't promise the structure of the date string, since it comes from third party. So it will be very dangerous to use the format pattern dd MMM yyyy HH:mm:ss:fff:fff:fff
As #Jeroen Mostert wrote the usage of string splitting is not a key factor when you use DateTime.ParseExact()
Also, if you really think efficiency is so important, don't assume any single call to DateTime.ParseExact will be "fast", or that any string splitting you do will be a bottleneck.
Well, isn't it simply this?
System.DateTime.ParseExact("12 NOV 2018 16:08:52:000:000:000",
"dd MMM yyyy HH:mm:ss:fff:fff:fff",
System.Globalization.CultureInfo.InvariantCulture)
This works if all groups of f have the same values, so for example all 0 or 123.
Tbh, i don't understand why you think that fff:ffffff:fffffffff matches 000:000:000
For my business needs, I don't need the part of micro/nano seconds.
You could make your second format working by cutting off the micro/nano part:
string date = "12 NOV 2018 16:08:52:000:000:000";
date = date.Remove(date.Remove(date.LastIndexOf(':')).LastIndexOf(':'));
DateTime result = System.DateTime.ParseExact(date, "dd MMM yyyy HH:mm:ss:fff", System.Globalization.CultureInfo.InvariantCulture);
Of course this assumes that there are always at least two colons. It's obvious that you need a try-catch to log invalid values and to continue with the next one.
Not an exact answer
System.DateTime.ParseExact("25 NOV 2018 16:08:52:000:000:000",
"dd MMM yyyy HH:mm:ss:fff:fff:fff", CultureInfo.InvariantCulture);
Things to consider: count of input string (000) should match with format(fff),
000 = fff good
00 = fff not good
000 = ff not good
You may need to manipulate input date string before trying to parse.
See this for more information regarding use of format specifier (fff)
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
.NET Fiddle:
https://dotnetfiddle.net/5UxCkd
I think that having same format for :fff is a key factor here
System.DateTime.ParseExact("12 NOV 2018 16:08:52:000:000:000","dd MMM yyyy H:mm:ss:fff:fff:fff", CultureInfo.InvariantCulture) seems to work
https://dotnetfiddle.net/ZAtchu example code
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'm based in the UK (GMT+1 time at the moment).
If I run this:
> DateTime.UtcNow.ToString("R") // Or...
> DateTime.Now.ToUniversalTime().ToString("R")
"Mon, 06 Oct 2014 10:20:00 GMT"
Correct answer.
If I now run the same, without UTC DateTime conversion:
> DateTime.Now.ToString("R")
"Mon, 06 Oct 2014 11:20:00 GMT"
The time printed is correct, but the timezone is wrong. I would expect instead:
"Mon, 06 Oct 2014 11:20:00" // Or..
"Mon, 06 Oct 2014 11:20:00 BST"
Question: Is this behaviour by design? Can I get the same output as with the "R" format, but with the correct timezone indicator?
It's definitely not a bug, it's the documented behaviour:
The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.
...
Although the RFC 1123 standard expresses a time as Coordinated Universal Time (UTC), the formatting operation does not modify the value of the DateTime object that is being formatted. Therefore, you must convert the DateTime value to UTC by calling the DateTime.ToUniversalTime method before you perform the formatting operation. In contrast, DateTimeOffset values perform this conversion automatically; there is no need to call the DateTimeOffset.ToUniversalTime method before the formatting operation.
As I noted in a comment on the question, 10:20 GMT is correct, assuming that you ran the code shortly before asking the question: 11:20 GMT has not occurred yet.
So basically, when you follow the guidance in the documentation and call ToUniversalTime, it does the right thing. When you don't, it gives a misleading value - that's unfortunate, but part of the broken design of DateTime IMO.
You should consider at least using DateTimeOffset, or potentially using my Noda Time project instead.
I am working on XML feed from RSS, i thinking of sorting the feed by their published date and time. Since different RSS feeds are being taken, they have different data and time formats.
for example
Sat, 23 Mar 2013 23:19:54 GMT
Sat, 23 Mar 2013 23:19:54 EDT
Sat, 23 Mar 2013 23:19:54 -0400
I want to convert them in local time and then sort them.
var rssFeed = from el in doc.Elements("rss").Elements("channel").Elements("item")
select new
{
Title = el.Element("title").Value,
Link = el.Element("link").Value,
Description = el.Element("description").Value,
PubDate = DateTime.Parse(el.Element("pubDate").Value, null,
DateTimeStyles.None)
};
Please let me know how to proceed.
may be your DateTime string is not in correct format to be parsed.
use this instead:
DateTime.ParseExact(el.Element("pubDate").Value,
"ddd, dd MM yyyy HH:mm:ss",null);
and pass your appropriate format to get your date.
you will have to get rid of that TimeZone portion in the end.
read more about this here and here
So, i have this string "Date: Mon Jan 03 2011 19:29:44 GMT+0200", and when i use DateTime.Parse(date).ToString(); i'm getting "String was not recognized as a valid DateTime."
If i remove the '+0200' part it works ok, but ofcourse it doesn't show the correct local time.
What's wrong with that?
From the documentation, it seems that DateTime.Parse() only understands:
The GMT designator, used alone, e.g. Mon, Jan 03 2011 17:29:44 GMT, or
A time zone offset specified without the GMT designator, e.g. Mon, Jan 03 2011 19:29:44+02:00.
You might want to convert your date string to the second form.
It just means that the time zone offset isn't an expected part of the default format strings.
If you know what format you're expecting, I suggest you call DateTime.ParseExact (or DateTime.TryParseExact), specifying the format(s) to try. Look at the documentation for custom date/time format strings for more details.
You have two mistakes.
First - don`t use Parse method. More correct is TryParse.
Second - you will have globalisation issues, when you use Parse or TryParse without arguments.
For example, see this code:
DateTime.Parse( "01.02.2011" ); In the USA it is 2nd of January. In the Germany it is 1st of February.
So, I recomment you to use formats from this article.