gpt4 book ai didi

c# - 仅在 C# 中将字符串转换为日期时间格式和日期

转载 作者:行者123 更新时间:2023-11-30 13:39:21 25 4
gpt4 key购买 nike

如何将字符串转换为日期时间。我有以下字符串:

08/19/2012 04:33:37 PM

我想将上面的字符串转换为以下格式的日期:

MM-dd-yyyy

dd/MM/yyyy HH:mm:ss

我一直在尝试使用不同的技术进行转换并使用以下方法:

DateTime firstdate = DateTime.Parse(startdatestring);

显示如下错误

String was not recognized as a valid DateTime.

我已经搜索过了,但无法得到确切的解决方案,也尝试对日期时间使用不同的格式。请问如何将上面的字符串转换为上面的日期格式

最佳答案

您需要先解析字符串 - 您遗漏了 AM/PM 指示符。看看Custom Date and Time Format Strings在 MSDN 上:

DateTime firstdate = DateTime.ParseExact(startdatestring, 
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);

然后你可以格式化为一个字符串:

var firstDateString = firstdate.ToString("MM-dd-yyyy");

您可能还想用 InvariantCulture 来做:

var firstDateString = firstdate.ToString("MM-dd-yyyy", 
CultureInfo.InvariantCulture);

关于c# - 仅在 C# 中将字符串转换为日期时间格式和日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com