[英]Cannot convert string to DateTime
I want to get a max date from the List<>. 我想从List <>获取最长日期。
But I don't know how to convert x.time
to DateTime. 但是我不知道如何将
x.time
转换为DateTime。
It always show error like this in exception: String was not recognized as a valid DateTime
. 它总是在异常中显示这样的错误:
String was not recognized as a valid DateTime
。
Here my code to do this: 这里是我的代码来做到这一点:
List<DTOSaveFromFile> lst = Load();
public static List<DTOSaveFromFile> Load()
{
string[] data = File.ReadAllLines(dataPath);
return (from i in data select new DTOSaveFromFile(i)).ToList<DTOSaveFromFile>();
}
foreach (var rows in lst)
{
DateTime biggest = lst
Select(x => DateTime.ParseExact(x.time, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture)) //to get the list of `string` of `time` from your List<DTOSaveFromFile> + //To convert it to DateTime
.Max(); //Get the max among the DateTime
}
x.time
from class: x.time
:
public class DTOSaveFromFile
{
public string reportName { get; set; }
public string eMail { get; set; }
public string time { get; set; }
}
How to resolve this problem? 如何解决这个问题? Thanks.
谢谢。
Add the format for your DateTime.ParseExact
to handle that 05-01-2016
case 添加
DateTime.ParseExact
的格式以处理05-01-2016
案例
string[] formats = new string[] {"d/M/yyyy", "d-M-yyyy"}; //notice the dash
Then your query would be like: 然后您的查询将是:
string[] formats = new string[] {"d/M/yyyy", "d-M-yyyy"}; //notice the dash
DateTime biggest = lst
.Select(x => DateTime.ParseExact(x.time, formats, //now use formats here
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeLocal)) //to get the list of `string` of `time` from your List<DTOSaveFromFile> + //To convert it to DateTime
.Max(); //Get the max among the DateTime
Note that there is additional parameters you may need to all in your DateTime.ParseExact
, which is System.Globalization.DateTimeStyles.AssumeLocal
. 请注意,您可能需要在
DateTime.ParseExact
所有其他参数,它们是System.Globalization.DateTimeStyles.AssumeLocal
。
Also, whenever you find an error due to new format
, just add that format
in the formats
array 另外,每当发现由于新
format
而产生的错误时,只需在formats
数组中添加该format
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.