仅在 C# 中将字符串转换为日期时间格式和日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12157799/
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 string to datetime format and date only in c#
提问by CodeManiac
How can I convert the string to datetime. I have following string:
如何将字符串转换为日期时间。我有以下字符串:
08/19/2012 04:33:37 PM
I want to convert above string to following format date:
我想将上述字符串转换为以下格式日期:
MM-dd-yyyy
and
和
dd/MM/yyyy HH:mm:ss
I have been trying to convert using different technique and using following:
我一直在尝试使用不同的技术并使用以下方法进行转换:
DateTime firstdate = DateTime.Parse(startdatestring);
It shows following error
它显示以下错误
String was not recognized as a valid DateTime.
字符串未被识别为有效的 DateTime。
I have search for it and couldn't get exact solution and also try using different format for datetime. Please how can I convert above string to above date format
我已经搜索过它,但无法获得确切的解决方案,还尝试对日期时间使用不同的格式。请问如何将上述字符串转换为上述日期格式
采纳答案by Oded
You need to parse the string first - you have missed out the AM/PM designator. Take a look at Custom Date and Time Format Stringson MSDN:
您需要先解析字符串 - 您错过了 AM/PM 指示符。看看MSDN上的自定义日期和时间格式字符串:
DateTime firstdate = DateTime.ParseExact(startdatestring,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
Then you can format to a string:
然后你可以格式化为一个字符串:
var firstDateString = firstdate.ToString("MM-dd-yyyy");
Which you may also want to do with InvariantCulture:
您可能还想这样做InvariantCulture:
var firstDateString = firstdate.ToString("MM-dd-yyyy",
CultureInfo.InvariantCulture);

