why does this not work?
DateTime.TryParseExact(text, "H", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out value);
I want to parse an Time value only providing the hour part, but it throws a FormatException.
On the other hand, this works:
DateTime.TryParseExact(text, "HH", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out value)
Anybody knows the cause?
Thanks.
Okay, I had to look this one up - it seems like it should be working, but it does not because the custom format string is not valid. A custom format string needs to be at least two characters wide - see:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers
So, according to the documentation, you can fix this by using this code:
DateTime.TryParseExact(text, "%H", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out value);
I guess this means that TryParseExact does not manage to fit the hour part into a single char, and that is understandable enough to me since hour will either be 12 or 24 hour based.
Without more specific information, the DatTime you're constructing can't determine AM / PM given the input. H would only allow a value of 1 - 12, leaving ambiguity. The HH provides the extra info.
The format specifier you pass to DateTime.TryParseExact needs to exactly match the string you are parsing.
E.g. passing "15:20" with format of "H" will fail, because there is other content in the string.
Either parse the whole string and use DateTime.Hour to just get the hour, or create a string with just the hour part and use Int32.Parse.
Related
I was looking in the Microsoft doc's and I can't find any explanation why ParseExact doesn't understand my date.
Could somebody explain why this code throws an exception?
DateTime.ParseExact("6092019", "dMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None)
From the docs: DateTime.ParseExact Method
If format is a custom format pattern that does not include date or
time separators (such as "yyyyMMddHHmm"), use the invariant culture
for the provider parameter and the widest form of each custom format
specifier. For example, if you want to specify hours in the format
pattern, specify the wider form, "HH", instead of the narrower form,
"H".
So in your case you probably should use approach suggested in John's answer - add "missing" zero and parse with wider date format "dd"
The problem here seems to be that d can be a one-digit or two-digit date, so the parser struggles to determine if "2102019" refers to the 2nd of November 2019, or the 21st of... and then it breaks. With delimiters, the parser is able to act more intelligently. It will happily parse "2-10-2019" using "d-MM-yyyy".
My suggested solution to your problem is to pad the string, and change your format string:
string dateToParse = "6092019";
string paddedDateToParse = dateToParse?.PadLeft(8, '0'); // 06092019
DateTime parsedDate = DateTime.ParseExact(paddedDateToParse, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);
Try it online
I have tried like below:
DateTime.ParseExact("Feb520161000PM",
"MMMdyyyyhhmmtt", CultureInfo.InvariantCulture)
But it's giving FormatException.
Interestingly
DateTime.ParseExact(DateTime.Now.ToString("MMMdyyyyhhmmtt"), "MMMdyyyyhhmmtt",
CultureInfo.InvariantCulture)
This is also giving format exception.
Alexei's answer is quite right, I wanna explain little bit deep if you let me..
You are thinking 5 should match with d specifier, right? But this is not how DateTime.ParseExact works under the hood.
Since The "d" custom format specifier represents number from 1 through 31, this specifier will map 52 in your string, not just 5. That's why your code throws FormatException.
As you can see, your string format can't parsed unless you do it some string manipulations with it.
In such a case, .NET Team suggests either using two digit forms like 05 or insert separators for your date and time values.
You can create a custom method that parse this MMMdyyyyhhmmtt format for only parse this kind of formatted strings like;
public static DateTime? ParseDate_MMMdyyyyhhmmtt(string date)
{
if (date == null)
return null;
if (date.Length < 14)
return null;
if (date.Length == 14)
date = date.Insert(3, "0");
DateTime dt;
if (DateTime.TryParseExact(date, "MMMdyyyyhhmmtt",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
return dt;
return null;
}
The format is not parseable with regular parsing which work from left to right - you need custom code that parses value from right to left instead as you want leftmost number to be variable width ("Feb111111111PM").
If possible - change format to one with fixed width fields (preferably ISO8601). Otherwise split string manually and construct date from resulting parts (time part would work fine by itself, so just need to manually parse date part).
Some other approaches and info can be found in similar post about time - DateTime.ParseExact - how to parse single- and double-digit hours with same format string?
I’m trying to parse a time. I’ve seen this question asked/answered here many times but not for this specific scenario. Here’s my code:
var time1 = DateTime.ParseExact("919", "Hmm", CultureInfo.InvariantCulture);
also
var time2 = DateTime.ParseExact("919", "Hmm", null);
both of these throw the same
"String was not recognized as a valid DateTime"
What I want is 9:19 AM.
For further info I also need to parse “1305” as 1:05 PM, this is working fine.
It seems to me I’m using the correct format. What am I overlooking?
I'm not sure there is any format that can handle this. The problem is that "H" can be either one digit or two, so if there are two digits available, it will grab both - in this case parsing it as hour 91, which is clearly invalid.
Ideally, you'd change the format to HHmm - zero-padding the value where appropriate - so "0919" would parse fine. Alternatively, use a colon in the format, to distinguish between the hours and the minutes. I don't believe there's any way of making DateTime parse a value of "919" as you want it to... so you'll need to adjust the string somehow before parsing it. (We don't have enough context to recommend a particular way of doing that.)
Yes, your format is right but since H specifier might be 2 character, ParseExact method try to parse 91 as an hour, which is an invalid hour, that's why you get FormatException in both case.
I connected to microsoft team about this situation 4 months ago. Take a look;
DateTime conversion from string C#
They suggest to use 2 digit form in your string or insert a date separator between them.
var time1 = DateTime.ParseExact("0919", "Hmm", CultureInfo.InvariantCulture);
or
var time1 = DateTime.ParseExact("9:19", "H:mm", CultureInfo.InvariantCulture);
You cant exclude the 0 prefix to the hour. This works
var time1 = DateTime.ParseExact("0919", "Hmm", CultureInfo.InvariantCulture);
Perhaps you want to just prefix 3-character times with a leading zero before parsing.
Much appreciated for all the answers. I don’t have control of the text being created so the simplest solution for me seemed to be prefixing a zero as opposed to adding a colon in the middle.
var text = "919";
var time = DateTime.ParseExact(text.PadLeft(4, '0'), "Hmm", null);
I've found how to turn a DateTime into an ISO 8601 format, but nothing on how to do the reverse in C#.
I have 2010-08-20T15:00:00Z, and I want to turn it into a DateTime object.
I could separate the parts of the string myself, but that seems like a lot of work for something that is already an international standard.
This solution makes use of the DateTimeStyles enumeration, and it also works with Z.
DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);
This prints the solution perfectly.
Although MSDN says that "s" and "o" formats reflect the standard, they seem to be able to parse only a limited subset of it. Especially it is a problem if the string contains time zone specification. (Neither it does for basic ISO8601 formats, or reduced precision formats - however this is not exactly your case.) That is why I make use of custom format strings when it comes to parsing ISO8601. Currently my preferred snippet is:
static readonly string[] formats = {
// Basic formats
"yyyyMMddTHHmmsszzz",
"yyyyMMddTHHmmsszz",
"yyyyMMddTHHmmssZ",
// Extended formats
"yyyy-MM-ddTHH:mm:sszzz",
"yyyy-MM-ddTHH:mm:sszz",
"yyyy-MM-ddTHH:mm:ssZ",
// All of the above with reduced accuracy
"yyyyMMddTHHmmzzz",
"yyyyMMddTHHmmzz",
"yyyyMMddTHHmmZ",
"yyyy-MM-ddTHH:mmzzz",
"yyyy-MM-ddTHH:mmzz",
"yyyy-MM-ddTHH:mmZ",
// Accuracy reduced to hours
"yyyyMMddTHHzzz",
"yyyyMMddTHHzz",
"yyyyMMddTHHZ",
"yyyy-MM-ddTHHzzz",
"yyyy-MM-ddTHHzz",
"yyyy-MM-ddTHHZ"
};
public static DateTime ParseISO8601String ( string str )
{
return DateTime.ParseExact ( str, formats,
CultureInfo.InvariantCulture, DateTimeStyles.None );
}
If you don't mind parsing TZ-less strings (I do), you can add an "s" line to greatly extend the number of covered format alterations.
using System.Globalization;
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00",
"s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal, out d);
Here is one that works better for me (LINQPad version):
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00Z",
#"yyyy-MM-dd\THH:mm:ss\Z",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out d);
d.ToString()
produces
true
8/20/2010 8:00:00 AM
It seems important to exactly match the format of the ISO string for TryParseExact to work. I guess Exact is Exact and this answer is obvious to most but anyway...
In my case, Reb.Cabin's answer doesn't work as I have a slightly different input as per my "value" below.
Value: 2012-08-10T14:00:00.000Z
There are some extra 000's in there for milliseconds and there may be more.
However if I add some .fff to the format as shown below, all is fine.
Format String: #"yyyy-MM-dd\THH:mm:ss.fff\Z"
In VS2010 Immediate Window:
DateTime.TryParseExact(value,#"yyyy-MM-dd\THH:mm:ss.fff\Z", CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal, out d);
true
You may have to use DateTimeStyles.AssumeLocal as well depending upon what zone your time is for...
This works fine in LINQPad4:
Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00Z"));
Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00"));
Console.WriteLine(DateTime.Parse("2010-08-20 15:00:00"));
DateTime.ParseExact(...) allows you to tell the parser what each character represents.
I'm trying out the DateTime.TryParseExact method, and I have come over a case that I just don't get. I have some formats and some subjects to parse that each should match one of the formats perfectly:
var formats = new[]
{
"%H",
"HH",
"Hmm",
"HHmm",
"Hmmss",
"HHmmss",
};
var subjects = new[]
{
"1",
"12",
"123",
"1234",
"12345",
"123456",
};
I then try to parse them all and print out the results:
foreach(var subject in subjects)
{
DateTime result;
DateTime.TryParseExact(subject, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault,
out result);
Console.WriteLine("{0,-6} : {1}",
subject,
result.ToString("T", CultureInfo.InvariantCulture));
}
I get the following:
1 : 01:00:00
12 : 12:00:00
123 : 00:00:00
1234 : 12:34:00
12345 : 00:00:00
123456 : 12:34:56
And to my question... why is it failing on 123 and 12345? Shouldn't those have become 01:23:00 and 01:23:45? What am I missing here? And how can I get it to work as I would expect it to?
Update: So, seems like we might have figured out why this is failing sort of. Seems like the H is actually grabbing two digits and then leaving just one for the mm, which would then fail. But, does anyone have a good idea on how I can change this code so that I would get the result I am looking for?
Another update: Think I've found a reasonable solution now. Added it as an answer. Will accept it in 2 days unless someone else come up with an even better one. Thanks for the help!
Ok, so I think I have figured this all out now thanks to more reading, experimenting and the other helpful answers here. What's happening is that H, m and s actually grabs two digits when they can, even if there won't be enough digits for the rest of the format. So for example with the format Hmm and the digits 123, H would grab 12 and there would only be a 3 left. And mm requires two digits, so it fails. Tadaa.
So, my solution is currently to instead use just the following three formats:
var formats = new[]
{
"%H",
"Hm",
"Hms",
};
With the rest of the code from my question staying the same, I will then get this as a result:
1 : 01:00:00
12 : 12:00:00
123 : 12:03:00
1234 : 12:34:00
12345 : 12:34:05
123456 : 12:34:56
Which I think should be both reasonable and acceptable :)
0123
012345
I'm guessing it looks for a length of 2/4/6 when it finds a string of numbers like that. Is 123 supposed to be AM or PM? 0123 isn't ambiguous like that.
If you do not use date or time
separators in a custom format pattern,
use the invariant culture for the
provider parameter and the widest form
of each custom format specifier. For
example, if you want to specify hours
in the pattern, specify the wider
form, "HH", instead of the narrower
form, "H"
cite:
http://msdn.microsoft.com/en-us/library/ms131044.aspx
As others have pointed out H is ambiguous because it implies a 10 hour day, where as HH is 12
To quote from MSDN's Using Single Custom Format Specifiers:
A custom date and time format string consists of two or more characters. For example, if the format string consists only of the specifier h, the format string is interpreted as a standard date and time format specifier. However, in this particular case, an exception is thrown because there is no h standard date and time format specifier.
To use a single custom date and time format specifier, include a space before or after the date and time specifier, or include a percent (%) format specifier before the single custom date and time specifier. For example, the format strings "h " and "%h" are interpreted as custom date and time format strings that display the hour represented by the current date and time value. Note that, if a space is used, it appears as a literal character in the result string.
So, should that have been % H in the first element in the formats array?
Hope this helps,
Best regards,
Tom.
I could be wrong, but I suspect it may have to do with the ambiguity inherent in the "H" part of your format string -- i.e., given the string "123", you could be dealing with hour "1" (01:00) or hour "12" (12:00); and since TryParseExact doesn't know which is correct, it returns false.
As for why the method does not supply a "best guess": the documentation is not on your side on this one, I'm afraid. From the MSDN documentation on DateTime.TryParse (emphasis mine):
When this method returns, contains the
DateTime value equivalent to the date
and time contained in s, if the
conversion succeeded, or
DateTime.MinValue if the
conversion failed. The conversion
fails if either the s or format
parameter is null, is an empty string, or does not
contain a date and time that
correspond to the pattern specified in
format. This parameter is passed
uninitialized.
"123" and "12345" seem to be ambiguous with respect to the TryParseExact method. "12345" could be either 12:34:50 or 01:23:45 for instance. Just a guess though.