fds
fds

Reputation: 59

Cannot convert string to DateTime

I want to get a max date from the List<>.

But I don't know how to convert x.time to DateTime.

It always show error like this in exception: 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:

public class DTOSaveFromFile
{
    public string reportName { get; set; }
    public string eMail { get; set; }
    public string time { get; set; }
}

How to resolve this problem? Thanks.

Upvotes: 1

Views: 615

Answers (1)

Ian
Ian

Reputation: 30813

Add the format for your DateTime.ParseExact to handle that 05-01-2016 case

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.

Also, whenever you find an error due to new format, just add that format in the formats array

Upvotes: 2

Related Questions