[英]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. 我想将dd-MM-yyyy日期格式解析为dd MMM yyyy我得到了引用,但是它不能以正确的方式转换日期,它与日期和月份不匹配。
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 . 但它返回2019年11月1日 。 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. 但是实际上是2019年1月11日,因为date的格式是dd-MM-yyyy我不知道如何更正它使用的任何解析方法都会返回2019年11月1日,这是错误的。 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);
Note that you'll get a FormatException
if you enter an invalid date here, so it might be better to use TryParse
: 请注意,如果您在此处输入无效的日期,则会得到FormatException
,因此使用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");
}
除John的出色回答外,以下是CultureInfo代码列表供您参考: http : //www.csharp-examples.net/culture-names/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.