DateTime.ParseExact "Hmmssff" FormatException [duplicate] - c#

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?

Related

How to convert datetime string in format MMMdyyyyhhmmtt to datetime object?

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?

Transform between datetime formats

I am facing a problem in which I need to transform dates in a given input format into a target one. Is there any standard way to do this in C#?
As an example say we have yyyy.MM.dd as the source format and the target format is MM/dd/yyy (current culture).
The problem arises since I am using a parsing strategy that gives priority to the current culture and then if it fails it tries to parse from a list of known formats. Now say we have two equivalent dates one in the source culture above (2015.12.9) and the other in the current culture (9/12/2015). Then if we attempt to parse this two dates the month will be 12 for the first case and in the second will be 9, so we have an inconsistency (they were supposed to mean be the same exact date).
I believe that if existing it should be something as
DateTime.Convert(2015.12.9, 'yyyy/MM/dd', CultureInfo.CurrentCulture).
Any ideas?
EDIT:
Thank you all for your ideas and suggestions, however the interpretation most of you gave to my question was not quite right. What most of you have answered is a direct parse in the given format and then a conversion to the CurrentCulture.
DateTime.ParseExact("2015.12.9", "yyyy.MM.dd", CultureInfo.CurrentCulture)
This will still return 12 as month, although it is in the CurrentCulture format. My question thus was, is there any standard way to transform the date in yyyy.MM.d to the format MM/dd/yyy so that the month is now in the correct place and THEN parsed it in the target culture. Such function is likely to be unexisting.
DateTime.ParseExact is what you are looking for:
DateTime parsedDate = DateTime.ParseExact("2015.12.9", "yyyy.MM.d", CultureInfo.InvariantCulture);
Or eventualy DateTime.TryParseExact if you're not confident with input string.
I know it's late but I try to explain little bit deep if you let me..
I am facing a problem in which I need to transform dates in any format
to a target one.
There no such a thing as dates in any format. A DateTime does not have any implicit format. It just has date and time values. Looks like you have a string which formatted as date and you want to convert another string with different format.
Is there any standard way to do this in C#?
Yes. You can parse your string with DateTime.ParseExact or DateTime.TryParseExact first with specific format to DateTime and then generate it's string representation with a different format.
As an example say we have yyyy.MM.dd as the source format and the
target format is MM/dd/yyy (current culture).
I didn't understand what is the meaning of current culture in this sentences and I assume you want yyyy not yyy, but you can generate it as I described above like;
string source = "2015.12.9";
DateTime dt = DateTime.ParseExact(source, "yyyy.MM.d", CultureInfo.InvariantCulture);
string target = dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture); // 12/09/201
The problem arises since I am using a parsing strategy that gives
priority to the current culture and then if it fails it tries to parse
from a list of known formats.
Since you didn't show any parsing strategy and there is no DateTime.Convert method in .NET Framework, I couldn't any comment.
Now say we have two equivalent dates one in the source culture above
(2015.12.9) and the other in the current culture (9/12/2015). Then if
we attempt to parse this two dates the month will be 12 and in the
second will be 9, so we have an inconsistency.
Again.. You don't have DateTime's. You have strings. And those formatted strings can't belong on any culture. Sure all cultures might parse or generate different string representations with the same format format a format does not belong any culture.
I assume you have 2 different string which different formatted and you wanna parse the input no matter which one it comes. In such a case, you can use DateTime.TryParseExact overload that takes string array for all possible formats as a parameter. Then generate it's string representation with MM/dd/yyy format and a culture that has / as a DateSeparator like InvariantCulture.
string s = "2015.12.9"; // or 9/12/2015
string[] formats = { "yyyy.MM.d", "d/MM/yyyy" };
DateTime dt;
if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture));
}
The Simple and Best way to do it is Using .ToString() Method
See this code:
DateTime x =DateTime.Now;
To Convert This Just Write like This:
x.ToString("yyyyMMdd")//20151210
x.ToString("yyyy/MM/dd)//2015/12/10
x.ToString("yyyy/MMM/dd)//2015/DEC/10 //Careful About M type should be capital for month .
Hope helpful

DateTime.TryParse - What was actually parsed?

I'm struggling a little bit in C# with DateTime.TryParse().
Essentially, given a string I need to extract the year and/or month and day in the current display culture. Sometimes I only get a year, or a month, or all three. Depending on what I get, I have a different control flow.
So far, I managed to parse a variety of strings into a DateTime; that isn't my problem.
My problem is that I wish to know WHAT was actually parsed (i.e. did I get a month or a year, or both).
The uninitialized DateTime defaults to 01/01/0001, and I cannot set everything to an invalid date, such as 99/99/9999 and then see what was filled.
I was thinking maybe I need to do regex, but the DateTime class provides that parsing for multiple cultures, which is very important in this project.
I've tried searching for this, but maybe I'm not using the right terms, because surely someone else must have had this issue before.
Update:
Here's some sample code of what I've got:
string strIn = Console.ReadLine();
DateTimeStyles enStyles = DateTimeStyles.AllowInnerWhite | DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.AssumeLocal;
bFound = DateTime.TryParse(strIn, CultureInfo.CreateSpecificCulture("en-US"), enStyles, out cDT);
Now, bFound will be true if something was parsed successfully. However, I need to know which parts of the date were parsed successfully
I dont understand you but are you looking for a specified format for your datetime?
string dateAndTimeFormat = "yyyy.MM.dd HH:mm:ss:fff"; // example of format
string dateAndTime = yourdatetimevalue;
DateTime toDateTime = DateTime.ParseExact(dateTime, dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture)
How formats are used:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx
EDIT 1
The tryparse returns true or false. False if it fails. Maybee that can be usefull?
Otherwise you can set the culture before the tryparse, if you are able to do so.
DateTime.TryParse(dateString, culture, styles, out dateResult)
Check the examples here :http://msdn.microsoft.com/en-us/library/9h21f14e.aspx
Under remarks:
"This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000)."
Hope some of that helps.
The DateTime.TryParse() returns value only on success.
So for below code example the variable dt is initialized to 01/01/0001 00:00:00 when declared.
When TryParse tries to extract date from string(MM/DD/YYYY format), and if it failes, then dt variable is having value 01/01/0001 00:00:00. Otherwise dt will contain the actual extracted datetime value (as in 2).
1)
DateTime dt;
DateTime.TryParse("23/15/2013", out dt);
// dt contains "01/01/0001 00:00:00"`
2)
`DateTime dt;
DateTime.TryParse("23/12/2013 6:25", out dt);
// dt contains "23/12/2013 06:25:00"`
There is no need to check WHAT was actually parsed.
Datetime value will be parsed if it's valid otherwise default datetime value will be returned.

DateTime.TryParseExact not working as expected

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.

C# - Regular Expression validating Date and Hour

I receive Date and time from CSV file
The received Date format is YYYYMMDD (string) (there is no ":" ,"-","/" to
separate Year month and date).
The received time format is HH:MM (24 Hour clock).
I have to validate both so that (example) (i) 000011990 could be invalidated for date (ii) 77:90 could be
invalidated for time.
The question is ,
Regular expression is the right candidate for do so (or) is there any other way to achieve
it?
You're looking for DateTime.TryParseExact:
string source = ...;
DateTime date;
if (!DateTime.TryParseExact(source,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date)) {
//Error!
}
You can use the same code to validate times, with the format string "HH:mm".
Your easiest solution would be to use
DateTime output;
if(!DateTime.TryParse(yourstring, out output))
{
// string is not a valid DateTime format
}
The DateTime.TryParse will attempt to convert your string to a DateTime variable, but it won't throw an exception if it fails - rather it return false if the string is not recognized as a valid DateTime.
I think a better way would be to use the date format class built into C#: DateTime.parse
You can use one of the TryParse methods of the DateTime struct. They will return false if they fail to parse.
Another option it use the ParseExact methods, but for those you need to specify a format provider.

Categories