如何将自定义字符串转换为有效日期时间

本文关键字:有效日期 时间 转换 字符串 自定义 | 更新日期: 2023-09-27 17:57:24

我得到一个string作为10 Apr, 2014 - 09:27,我希望它与当前DateTime进行比较,看看它是更低还是更高。

上面给出了一个错误,如Not recognized as Valid DateTime

如何正确转换?

我需要先将日期格式化为某种格式等吗?

如何将自定义字符串转换为有效日期时间

使用DateTime.ParseExactDateTime.TryParseExact(如果格式可能无效)。

这适用于您的示例:

DateTime dt = DateTime.ParseExact("10 Apr, 2014 - 09:27", "dd MMM, yyyy - HH:mm", CultureInfo.InvariantCulture);

我正在使用CultureInfo.InvariantCulture来确保它适用于英文月份名称,即使当前文化不同。如果小时不是 24 小时格式,则需要将HH更改为 hh

要与当前时间使用DateTime.Now进行比较:

if(dt > DateTime.Now)
{
    // ...
}
您可以使用

DateTime.ParseExact函数并为其提供您期望的自定义格式。

您可以使用此链接来完成您所要求的内容:

如何在 C# 中比较日期时间?

代码片段(来自提供的链接):

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
// The example displays the following output:
//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM

希望有帮助。