How to parsing dates c#



So far, we have worked with dates defined directly in code, but you will probably quickly run into a situation where you need to work with a date specified by the user. This is a surprisingly complicated subject because there are so many ways of writing a date. The .NET framework can help you with this, because it supports all the cultures, as illustrated in previous examples, but you still need to help the user specify the date in the format you expect. After that, you can use the Parse() metho

var usCulture = new System.Globalization.CultureInfo("en-US");
Console.WriteLine("Please specify a date. Format: " + usCulture.DateTimeFormat.ShortDatePattern);
string dateString = Console.ReadLine();
DateTime userDate = DateTime.Parse(dateString, usCulture.DateTimeFormat);
Console.WriteLine("Date entered (long date format):" + userDate.ToLongDateString());

However, be aware that the Parse() method is very strict - if the user doesn't enter the date in the expected format, it will throw an exception. For that reason, it's usually a good idea to use the TryParse() method instead - it does the exact same thing, but it allows you to check if the date could be parsed or not, and it doesn't throw an exception. Here's a revised version of the previous example:

var usCulture = new System.Globalization.CultureInfo("en-US");
Console.WriteLine("Please specify a date. Format: " + usCulture.DateTimeFormat.ShortDatePattern);
string dateString = Console.ReadLine();
DateTime userDate;
if (DateTime.TryParse(dateString, usCulture.DateTimeFormat, System.Globalization.DateTimeStyles.None, out userDate))
    Console.WriteLine("Valid date entered (long date format):" + userDate.ToLongDateString());
else
    Console.WriteLine("Invalid date specified!");

0 Comment's

Comment Form

Submit Comment