user10753256
user10753256

Reputation: 141

Parsing date form dd-MM-yyyy to dd MMM yyyy

I want to parse dd-MM-yyyy date format into dd MMM yyyy I get the reference but it cannot convert date in a proper manner it mismatches the date and month.

Suppose my date is

string dat = "11-01-2019"

and I am using

string date = DateTime.Parse(dat).ToString("dd MMM yyyy");

but it returns 01 Nov 2019. But actually, it is 11 Jan 2019 because the format of date is dd-MM-yyyy I don't understand how to correct it any method of parsing I am using it returns 01 Nov 2019 that is wrong. Please help me to resolve the issue

Upvotes: 0

Views: 292

Answers (2)

Mariano Luis Villa
Mariano Luis Villa

Reputation: 497

Adding to John's great answer, here's a list of CultureInfo codes for reference: http://www.csharp-examples.net/culture-names/

Upvotes: 0

ProgrammingLlama
ProgrammingLlama

Reputation: 38757

You'll need to specify the culture the date is formatted for. I'm assuming UK here:

var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
string date = DateTime.Parse(dat, ukCulture).ToString("dd MMM yyyy");
Console.WriteLine(date);

Try it online

Note that you'll get a FormatException if you enter an invalid date here, so it might be better to use TryParse:

var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
DateTime parsedDate;
if (DateTime.TryParse(dat, ukCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
    string date = parsedDate.ToString("dd MMM yyyy");
    Console.WriteLine(date);
}
else
{
    Console.WriteLine("invalid date");
}

Try it online

Upvotes: 2

Related Questions