DateTime.ParseExact - 英国日期和时间

本文关键字:时间 日期 英国 ParseExact DateTime | 更新日期: 2023-09-27 17:55:14

我正在尝试解析以下英国格式DateTime字符串:24/01/2013 22:00

但是,我不断收到此错误:

字符串未被识别为有效的日期时间。

CultureInfo.CurrentCulture返回正确的"en-GB"

这是我的代码

    [TestMethod]
    public void TestDateTimeParse()
    {
        DateTime tester = DateTime.ParseExact("24/01/2013 22:00", "d/M/yyyy hh:mm", CultureInfo.CurrentCulture);
        int hours = tester.Hour;
        int minutes = tester.Minute;
        Assert.IsTrue(true);
    }

DateTime.ParseExact - 英国日期和时间

hh表示 12 小时制。您应该改用HH

DateTime.ParseExact("24/01/2013 22:00", 
                    "d/M/yyyy HH:mm", // <-- here
                    CultureInfo.CurrentCulture)

"hh" 表示小时,使用 12 小时制从 01 到 12

"HH" 表示小时,使用 24 小时制从 00 到 23

尝试这样;

public static void Main(string[] args)
{
    DateTime tester = DateTime.ParseExact("24/01/2013 22:00", "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
}

这是一个DEMO.

您也可以从 MSDN 查看Custom Date and Time Format Strings

你的格式是错误的,试试这个:

DateTime tester = DateTime.ParseExact("24/01/2013 22:00", "dd/MM/yyyy HH:mm", CultureInfo.CurrentCulture);