c# - 在 C# 中将类似 java 的日期字符串转换为 DateTime

标签 c# datetime

我有以下格式的日期:

Tue Mar 13 12:00:00 EST 2012

如何在 C#.net 中将它们转换为 DateTime?

最佳答案

您可以使用 TryParseExact :

class Program
{
    static void Main(string[] args)
    {
        var dtString = "Tue Mar 13 12:00:00 EST 2012".ConvertTimeZone();
        DateTime dt;
        var success = DateTime.TryParseExact(
            dtString,
            "ddd MMM dd HH:mm:ss zzz yyyy",
            CultureInfo.InvariantCulture,
            DateTimeStyles.None,
            out dt);

        Console.WriteLine(success);
        if (Debugger.IsAttached) { Console.ReadKey(); }
    }
}

public static class Extensions
{
    private static Dictionary<string, string> _timeZones =
        new Dictionary<string, string> { { "EST", "-05:00" } };

    public static string ConvertTimeZone(this string s)
    {
        var tz = s.Substring(20, 3);
        return s.Replace(tz, _timeZones[tz]);
    }
}

如果转换成功,success将是 truedt将具有日期和时间值。

好吧,让我们稍微谈谈这个。实际上,我不得不下潜并 promise 将时区实际转换为偏移量。这是非常准确的,但需要一些维护。您唯一需要维护的是 Dictionary<string, string> _timeZones .您需要添加您想要支持的所有时区。

关于c# - 在 C# 中将类似 java 的日期字符串转换为 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20660573/

相关文章:

javascript - 正则表达式限制小数点后两位

c# - 我怎样才能改进 LINQ?

c# - 在 Windows 浏览器窗体中停用鼠标中键移动

python - 如果在列中,则无法减去日期时间和 NaT

python - 修改pandas dataframe的日期索引

Python:在 pandas 中计数后对日期进行排序

mysql - 如何使用特定格式插入当前日期时间

c# - 调用链中同一装饰器的多次注册

c# - 在android和windows之间同步文件的最佳方式

python - 在 Pandas 中将 GroupBy 与 DateTime 结合使用 (Python)