I'm having trouble using DateTime.Parse
I'm handling a variety of formats of dates and some of which are of the formatJanuary 11th
or February 22nd
and so on.
DateTime.Parse
throws an exception trying to parse these sort of dates.
I was wondering if there is a built in functionality in DateTime that I am missing, like a flag I can set that will make Parse behave in a more acceptable way.
I am aware that this is solvable with a relatively simple regular expression, moreover I already have a class that fuzzy matches dates that I wrote, however I would like to know if there is a built in way to perform this sort of extraction since it will more likely be easier to maintain in the long run than reinventing the wheel.
The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.
You'll notice that each number has a corresponding ordinal number that ends in one of the following suffixes: –st, –nd, –rd, or –th.
The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.
I had similar problem here's better way
stringdate="August 19th 2000"
string pattern = @"\b(\d+)(?:st|nd|rd|th)\b";
Regex rgx = new Regex(pattern);
DateTime.Parse(String.Format("{0:MMMM, d, yyyy}", rgx.Replace(stringdate, "$1"))
**result** {19/08/2000 00:00:00} System.DateTime
From Microsoft and regex to remove ordinals and How can I visualize the way various DateTime formats will display?
EDIT
If the year is not specified:
stringdate= rgx.Replace(stringdate, "$1");
DateTime datetime;
if (!DateTime.TryParseExact(stringdate, "MMMM dd yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None, out datetime))
{
// assuming no gap exist
datetime = DateTime.Parse(stringdate += " "+DateTime.Now.Year);
}
Now if the input string text is "June 11th"
, it will be 11/6/2021
.
There are More functions and ways to handle dates at DateTime Documentation.
If you dont want the year at all, then you can add the following line:
datetime.ToString("MM/dd");
Now the output will be "11/6"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With