从奇怪的格式解析 c# 中的日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2235065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:37:25  来源:igfitidea点击:

Parse DateTime in c# from strange format

c#datetimeparsingformatculture

提问by Grant

if i have a datetime string in a weird format, such as YYYY##MM##DD HH**M**SS, how can i create a new datetime object base on that? i have read something about the datetimeformatinfoclass but not sure how to get it working..

如果我有一个奇怪格式的日期时间字符串,例如YYYY##MM##DD HH**M**SS,我如何基于它创建一个新的日期时间对象?我已经阅读了一些关于 datetimeformatinfoclass 的内容,但不知道如何让它工作..

采纳答案by Jon Skeet

You can use DateTime.ParseExact, or DateTime.TryParseExact for data which you're not confident in. For example:

您可以将 DateTime.ParseExact 或 DateTime.TryParseExact 用于您不确定的数据。例如:

using System;

class Test
{
    static void Main()
    {
        string formatString = "yyyy'##'MM'##'dd' 'HH'*'mm'*'ss";
        string sampleData = "2010##02##10 07*22*15";
        Console.WriteLine(DateTime.ParseExact(sampleData,
                                              formatString,
                                              null));
    }
}

The quotes in the format string aren't strictly necessary - this will work too:

格式字符串中的引号不是绝对必要的 - 这也可以:

string formatString = "yyyy##MM##dd HH*mm*ss";

However, using the quotes means you're being explicit that the characters between the quotes are to be used literally, and not understood as pattern characters - so if you changed "#" to "/" the version using quotes would definitely use "/" whereas the version without would use a culture-specific value.

但是,使用引号意味着您明确表示引号之间的字符将按字面使用,而不是理解为模式字符 - 因此,如果您将“#”更改为“/”,则使用引号的版本肯定会使用“/ " 而没有的版本将使用特定于文化的值。

The nullin the call to ParseExactmeans "use the current culture" - in this case it's unlikely to make much difference, but a commonly useful alternative is CultureInfo.InvariantCulture.

null在调用ParseExact表示“使用目前的文化” -在这种情况下,它不会带来多大的改变,但是一个常用有用的替代是CultureInfo.InvariantCulture

It's unfortunate that there's no way of getting the BCL to parse the format string and retain the information; my own Noda Timeproject rectifies this situation, and I'm hoping it'll make parsing and formatting a lot faster - but it's far from production-ready at the moment.

不幸的是,没有办法让 BCL 解析格式字符串并保留信息;我自己的Noda Time项目纠正了这种情况,我希望它能让解析和格式化的速度更快——但目前还远未准备好生产。

回答by Giorgi

You can use DateTime.ParseExactmethod and pass the format you need.

您可以使用DateTime.ParseExact方法并传递您需要的格式。