Date Parsing(formatted) from string in .NET

There are many functions in DateTime class in .NET to parse a string and get a date.

Usually DateTime.TryParse() tries to parse the date from string for a set of formats like 'mm-dd-yyyy', 'mm-dd-yy', or like 'dd-monthname-yyyy' but cannot parse from 'dd-mm-yyyy' (e.g. '15-10-2008').

To parse a string to a date in your own defined format use




DateTime.ParseExact();



For example to parse a date from a string like '15-10-2008' which is '15-Oct-2008'
where month and day can be double or single digit you can use-


string dateStr='15-10-2008';
DateTime parsedDate=DateTime.ParseExact(dateStr, "d-M-yyyy",

System.Globalization.CultureInfo.InvariantCulture);

Comments