且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中将字符串(yyyyMMddhhmm)转换为DateTime的函数

更新时间:2023-02-03 08:06:51

绝对-使用 DateTime.ParseExact

Absolutely - use DateTime.ParseExact:

DateTime parsed = DateTime.ParseExact(text, "yyyyMMddHHmm",
                                      CultureInfo.InvariantCulture);

请注意 HH 24小时 hh 的格式表示为12小时格式。

Note the HH for 24-hour instead of hh for 12-hour format.

或者,您可以使用 DateTime.TryParseExact ,它会返回一个true / false值,指示解析是否成功。如果您完全希望所有数据都是有效的,否则抛出异常是合理的,那么 DateTime.ParseExact 很好。

Alternatively, you could use DateTime.TryParseExact, which returns a true/false value to indicate whether or not the parsing was successful. If you're fully expecting all the data to be valid, and it's reasonable for an exception to be thrown otherwise, then DateTime.ParseExact is fine.

作为一种非常不同的替代方法,您可以使用诺达时间

As a very different alternative, you could use Noda Time:

// Do this once...
var pattern = LocalDateTimePattern.CreateWithInvariantInfo("yyyyMMddHHmm");

// Do this repeatedly...
var parseResult = pattern.Parse(text);
if (parseResult.Success)
{
    LocalDateTime value = parseResult.Value;
    // Use the value...
}
else
{
    // Error... 
}

或者对于只是抛出异常的行为,只需使用 parseResult.Value

Or for the "just throw an exception" behaviour, just use parseResult.Value unconditionally.

编辑:顺便说一句,有什么理由为什么将日期存储在varchar列中?您可以改成自己的方案吗?

As an aside, is there any reason why you're storing dates in a varchar column? Can you fix your schema instead?