C# 将日期时间转换为英国格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14704289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert DateTime to UK format
提问by nick gowdy
I want to convert the date "01/22/2013 10:00:00" to "22/01/2013 10:00:00" and my method doesn't recognise my date string.
我想将日期“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");
I am getting this error:
我收到此错误:
System.FormatException - String was not recognized as a valid DateTime.
System.FormatException - 字符串未被识别为有效的 DateTime。
What is the correct string format for ParseExact?
ParseExact 的正确字符串格式是什么?
回答by Lloyd
Your date formatting is wrong, for the US it would be 01/22/2013 10:00:00
which is MM/dd/yyyy HH:mm:ss
. For the UK it would be dd/MM/yyyy
etc.
您的日期格式是错误的,对于美国来说,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");
Note I am assuming a 24 hour clock here which is why I use HH
. If you wanted a twelve hour clock you'd need hh
but then you should also put AM/PM etc.
注意我在这里假设 24 小时制,这就是我使用HH
. 如果你想要一个 12 小时制的时钟,你需要,hh
但你也应该把 AM/PM 等。
回答by daryal
You are using slashes and you have "seconds" part in your date string. You need to change the format provided in the ParseExact
method:
您正在使用斜杠,并且日期字符串中有“秒”部分。您需要更改ParseExact
方法中提供的格式:
string StartDate = "01/22/2013 10:00:00";
DateTime dt = DateTime.ParseExact(StartDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
StartDate = dt.ToString("dd/M/yyyy");
回答by Mohammad Dehghan
Use this code:
使用此代码:
DateTime dt = DateTime.ParseExact(StartDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
StartDate = dt.ToString("dd/MM/yyyy hh:mm:ss");
Notice the change to format string of ParseExact
.
请注意对格式字符串的更改ParseExact
。
回答by Mehmet Ata?
Try this
尝试这个
var str = "01/22/2013 10:00:00";
var date = DateTime.ParseExact(str, "MM/dd/yyyy HH:mm:ss", new CultureInfo("en-GB"));
var res = date.ToString("dd/MM/yyyy HH:mm:ss", new CultureInfo("en-GB"));
Console.WriteLine(res);
Console.WriteLine("22/01/2013 10:00:00" == res);