简体   繁体   中英

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

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

除John的出色回答外,以下是CultureInfo代码列表供您参考: http : //www.csharp-examples.net/culture-names/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM