Skip to main content
 首页 » 编程设计

c#之Convert.ToDateTime 在 C# 从特定日期字符串

2024年02月20日28xiaohuochai

我有一个特定的日期string:"13/02/07,16:05:13+00"

我试图将它在 C# 中转换为 datetime (Convert.toDateTime),但我一直收到错误。

我也尝试过使用下面的代码解析它,但没有成功:

 DateTime dt = DateTime.ParseExact(date, "yy/MM/dd,hh:mm:ss+00",System.Globalization.CultureInfo.CurrentCulture); 

对于真正特定的 datetime string,我如何将 string 转换为 datetime。

请您参考如下方法:

不要使用 CurrentCulture - 使用不变的文化。否则,您将选择当前区域性的日期和时间分隔符。

此外,您需要使用 HH 而不是 hh,因为您使用的是 24 小时制,而不是 12 小时制。这很好用:

using System; 
using System.Collections.Generic; 
using System.Globalization; 
 
class Test 
{ 
    static void Main() 
    { 
        string date = "13/02/07,16:05:13+00"; 
        DateTime dt = DateTime.ParseExact(date, "yy/MM/dd,HH:mm:ss+00", 
                                          CultureInfo.InvariantCulture); 
        Console.WriteLine(dt); 
    } 
} 

“+00”肯定总是一样的吗?如果您需要处理非零偏移量,它会稍微改变一下。