在C#中将字符串(yyyyMMddhhmm)转换为DateTime的函数
在我的数据库中,我有一个字段类型为 varchar 的日期,该日期以以下格式存储 yyyyMMddhhmm ,没有空格或其他字符将它们分隔。
In my database I have a field date of type varchar where the date is stored in the following format yyyyMMddhhmm, with no spaces or other characters separating them.
现在我需要将此日期与C# DateTime 进行比较,因此我需要将字符串转换为 DateTime 。我能想到的最合乎逻辑的方法是从变量 date
中提取与年,月和日相关的子字符串,然后创建一个新的 DateTime 对象:
Now I need to compare this date with a C# DateTime, therefore I need to convert the string into DateTime. The most logical way that I can think of is to extract from the variable date
the sub-string related to year, month and day and create a new DateTime object:
var year = Convert.ToInt32(date.Substring(0, 4));
var month = Convert.ToInt32(date.Substring(4, 2));
var day = Convert.ToInt32(date.Substring(6, 2));
DateTime dateToCompare = new DateTime(year, month, day);
有没有可用的C#方法允许我执行此转换而无需编写所有这些代码?
Is there any available C# method that allows me to perform this conversion without writing all this code?
绝对-使用 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?