Arianule
Arianule

Reputation: 9043

String was not recognized as a valid DateTime when trying to filter data using linq

I am trying to filter data by date and the date format of the field is short date. The dates I am filtering on thus looks like this example '16-12-2017'.

The query I am using looks as follow.

  data = data.Where(d => DateTime.ParseExact(d.InteractionDate, "dd-MM-yyyy", CultureInfo.InvariantCulture) >= DateTime.ParseExact(filter.StartDate, "dd-MM-yyyy", CultureInfo.InvariantCulture)
                                     && DateTime.ParseExact(d.InteractionDate, "dd-MM-yyyy", CultureInfo.InvariantCulture) <= DateTime.ParseExact(filter.EndDate, "dd-MM-yyyy", CultureInfo.InvariantCulture)).ToList();

Examples

StartDate = "01-12-2017"
EndDate = "16-12-2017"
IntersectionDate = "20-06-2017"

On my local machine this works fine but when published to IIS I get the error.

String was not recognized as a valid DateTime

How can I overcome this error?

Thanks

Upvotes: 1

Views: 478

Answers (1)

gembird
gembird

Reputation: 14053

On the server the string is probably not formated like dd-MM-yyyy but differently. It is necessary to find out, how on the server the strings looks like.

The filtering could use e.g. function like ParseDateTime which will receive array of predefined formats so the code works with different formats on local machine as well as on server etc.

data = data.Where(d => ParseDateTime(d.InteractionDate, DateTimeFormats) >= ParseDateTime(filter.StartDate, DateTimeFormats) &&
                       ParseDateTime(d.InteractionDate, DateTimeFormats) <= ParseDateTime(filter.EndDate, DateTimeFormats))
                       .ToList();

E.g. the function will contain logging so when error occurs then the date time string can be found in the log file and the correct format can be appended to formats array used.

private static DateTime ParseDateTime(string dateTimeString, string[] formats)
{
    try
    {
        DateTime dateStamp = DateTime.ParseExact(dateTimeString, 
            formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
        return dateStamp;
    }
    catch (Exception ex)
    {
        Logger.Error(ex, $"dateTimeString: '{dateTimeString}', '{string.Join(",", formats)}'.");
        throw;
    }
}

Example of how the predefined formats could look like. HTH

public string[] DateTimeFormats => new string[]
{
    "dd-MM-yyyy",
    "MM/dd/yyyy",
    "dd/MM/yyyy",
    "M/d/yyyy",
    "d.M.yyyy",
    "dd.MM.yyyy",
    "MM/dd/yyyy",
    "M/d/yyyy"
};

Upvotes: 1

Related Questions