[英]convert string to datetime format and date only in c#
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.字符串未被识别为有效的日期时间。
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请问如何将上面的字符串转换为上面的日期格式
You need to parse the string first - you have missed out the AM/PM designator.您需要先解析字符串 - 您错过了 AM/PM 指示符。 Take a look at Custom Date and Time Format Strings on MSDN:查看 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);
In .NET 6 you can use the DateOnly struct在.NET 6中,您可以使用DateOnly 结构
var dateTime = DateTime.Parse("08/19/2012 04:33:37 PM");
var dateOnly = DateOnly.FromDateTime(dateTime);
var dateOnlyString = dateOnly.ToString("MM-dd-yyyy");
or或者
var dateOnlyString = DateOnly.Parse("08/19/2012").ToString("MM-dd-yyyy");
Output: 08-19-2012
输出: 08-19-2012
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.