将DateTime转换为英国格式

nic*_*wdy 13 c# datetime

我想将日期"01/22/2013 10:00:00"转换为"22/01/2013 10:00:00",我的方法无法识别我的日期字符串.

 DateTime dt = DateTime.ParseExact(StartDate, "MM dd yyyy h:mm", CultureInfo.InvariantCulture);
            StartDate = dt.ToString("dd/M/yyyy");
 dt = DateTime.ParseExact(EndDate, "MMM dd yyyy h:mm", CultureInfo.InvariantCulture);
            EndDate = dt.ToString("dd/M/yyyy");
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

System.FormatException - String未被识别为有效的DateTime.

ParseExact的正确字符串格式是什么?

Llo*_*oyd 15

你的日期格式是错误的,对美国来说就是01/22/2013 10:00:00这样MM/dd/yyyy HH:mm:ss.对于英国来说,它将是dd/MM/yyyy等等.

DateTime dt = DateTime.ParseExact(StartDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

dt.ToString("dd/MM/yyyy");
Run Code Online (Sandbox Code Playgroud)

注意我假设这里有24小时制,这就是我使用的原因HH.如果你想要一个十二小时的时钟你需要,hh但你也应该把AM/PM等.


Moh*_*han 5

使用此代码:

DateTime dt = DateTime.ParseExact(StartDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
            StartDate = dt.ToString("dd/MM/yyyy hh:mm:ss");
Run Code Online (Sandbox Code Playgroud)

注意格式化字符串的更改ParseExact.