从txt文件读取的DateTime
问题描述:
如何读取类似("05.10/2012 5:30:29 PM")的字符串并在DateTime值中使用它?
How to read a string like ("05.10/2012 5:30:29 PM") and use it in a DateTime value ?
答
Hello
试试这个:
Hello
Try this:
DateTime myDateTime = DateTime.Parse("05.10/2012 5:30:29 PM");
或
or
DateTime myDateTime;
DateTime.TryParse("05.10/2012 5:30:29 PM", out myDateTime)
详细信息: http://msdn.microsoft.com/en-us/library/1k1skd40.aspx [ ^ ]
More information: http://msdn.microsoft.com/en-us/library/1k1skd40.aspx[^]
假设每个日期都在单独的行中,则可以使用
读取所有日期
Assuming each date is on a separate line, you can read them all with
string[] lines = File.ReadAllLines(path);
然后,您可以使用Datetime.ParseExact或DateTime.TryParseExact将每个转换为DateTime:
You can then convert each one to a DateTime using Datetime.ParseExact, or DateTime.TryParseExact:
foreach (string line in lines)
{
DateTime dt = DateTime.ParseExact(line, "dd.MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
...
}
这里有一个DateTime格式代码列表:为显示-格式字符串说明 [ ^ ]
There is a list of DateTime format codes here: Formatting a DateTime for display - format string description[^]