日期时间字符串解析 [英] DateTime string parsing

查看:170
本文介绍了日期时间字符串解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经解析的ASCII文件做了一个通用的解析器。 当我想解析日期,我用ParseExact功能DateTime对象来分析,但我得到的问题的一年。

I have made a generic parser for parsing ascii files. When I want to parse dates, I use ParseExact function in DateTime object to parse, but I get problems with the year.

解析文本,即090812与parseExact字符串YYMMDD。

The text to parse is i.e. "090812" with the parseExact string "yyMMdd".

我希望得到一个DateTime对象说:12 / 8-2009,但我得到12 / 8-1909。 我知道,我可以通过解析它之后,从而修改年作出丑陋的解决方案。

I'm hoping to get a DateTime object saying "12/8-2009", but I get "12/8-1909". I know, that I could make an ugly solution by parsing it afterwards, and thereby modifying the year..

任何人都知道的一个聪明的办法来解决这个问题?

Anyone know of a smart way to solve this ??

在此先感谢。

瑟伦

推荐答案

这样的理论上优雅的方式:改变日历的 TwoDigitYearMax 属性使用的的DateTimeFormatInfo 您使用分析文本。例如:

Theoretically elegant way of doing this: change the TwoDigitYearMax property of the Calendar used by the DateTimeFormatInfo you're using to parse the text. For instance:

CultureInfo current = CultureInfo.CurrentCulture;
DateTimeFormatInfo dtfi = (DateTimeFormatInfo) current.DateTimeFormat.Clone();
// I'm not *sure* whether this is necessary
dtfi.Calendar = (Calendar) dtfi.Calendar.Clone();
dtfi.Calendar.TwoDigitYearMax = 1910;

然后使用 dtfi 在调用 DateTime.ParseExact

这样的实用方法:加上20到你输入的开始,并解析了年月日

Practical way of doing this: add "20" to the start of your input, and parse with "yyyyMMdd".

这篇关于日期时间字符串解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆