问题描述
我需要接受文本文件中的DateTime
或Date
信息.挑战在于,此日期信息每次都以任何格式出现.可以采用以下任何格式.
I need to accept either DateTime
or Date
information from a text file. The challenge is, this date information comes in any format each time. It can be in any format below.
20160131 23:30:15
31032016 23:30:15
2016/01/31 23:30:15
01/31/2016 23:30:15
31/01/2016 23:30:15
31.01.2016 23:30:15
31/01/2016 23:30
// ... more formats come with '-' separators as well and some similar format
如何将这些随机格式统一为string
甚至直接统一为DateTime
?还是有任何第三方库可以处理这种情况?
How can I unify these random formats into a string
or even straight into DateTime
? Or is there any 3rd party library that can handle this scenario?
推荐答案
使用TryParseExact
(或ParseExact
)并将所有格式指定为数组string[] formats
Use TryParseExact
(or ParseExact
) and specify all of the format into an array string[] formats
string[] formats = { "yyyyMMdd HH:mm:ss", "ddMMyyyy HH:mm:ss",
"yyyy/MM/dd HH:mm:ss", "MM/dd/yyyy HH:mm:ss" }; //and so on, add more
string dtText = "01/31/2016 23:30:15"; //example
DateTime dt;
bool result = DateTime.TryParseExact(dtText, formats, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal, out dt);
有了这个,就可以处理所有指定的 DateTime
格式.
Once you have this, then you could handle all the specified DateTime
formats.
请注意,统一所有可能的DateTime
格式是不可能的,因为其中某些格式是相互排斥的:
Note that it is impossible for you to unify all possible DateTime
formats since some of them are mutually exclusive:
Given an ambiguous case:
"12-12-2012"
and formats:
"dd-MM-yyyy"
"MM-dd-yyyy"
以上两种方法中只能使用一种格式.
There can only be one format to be used among the two above.
这就是为什么,根据您的需要为每个项目进行自定义非常有用.
That's why, it is good for you to customize for each project depending on your need.
如果您希望此代码可重用和自定义,建议您创建一个主文件(.txt
或.xml
),该文件存储您可能要在项目中使用的所有DateTime
格式.
If you want this to be reusable and customizable, I recommend you to create a master file (.txt
or .xml
) which stores all the DateTime
formats which you might want to use in your projects.
masterdtformat.txt
"yyyy/MM/dd HH:mm:ss"
"yyyyMMdd HH:mm:ss"
"ddMMyyyy HH:mm:ss"
"MM/dd/yyyy HH:mm:ss"
"dd-MMM-yyyy HH:mm:ss"
//and so on...
然后,每当您有一个项目时,只需要将某些格式从主文件转换为特定的项目文件.然后在项目中,加载该项目文件以提供所需的所有格式.
Then, whenever you have a project, you simply need to take some formats from your master file to your particular project file. And in the project, you load that project file to give all the formats you need.
projectdtformat.txt
"yyyy/MM/dd HH:mm:ss"
"yyyyMMdd HH:mm:ss"
//suppose you only need two
这样,无论您一次指定的格式如何,都可以重用.通过更改项目文件,很容易完成为给定项目提供有效的DateTime
格式的机制.
This way, whatever format you have specified once, will be reusable. And the mechanism to provide valid DateTime
formats for a given project will also be done quite easily by changing the project file.
这篇关于如何统一各种DateTime格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!