Home > Mobile >  How to filter between a dates from string and datetimepicker
How to filter between a dates from string and datetimepicker

Time:04-08

I am trying to filter through things by date. I have 2 DateTimePicker called FromDate and ToDate. I have an array and within one of the array (str[10]) is a date, I tried converting the string into a datetime format but I still get the error:

System.FormatException: 'String was not recognized as a valid DateTime.'

The string within str[10]:

str[10] = "9/22/2017 18:24";

My current code:

string[] date = str[10].Split(' ');                            
DateTime dateSpec = DateTime.ParseExact(date[0], "MM/dd/yyyy", CultureInfo.CurrentCulture);
if (dateSpec >= FromDate.Value && dateSpec <= ToDate.Value) 
{ 
   //Do Something
}

I am not so sure what to do as most forums suggest more or less the same thing. I'm not sure where the error is. I checked the array and the string does not have any spaces as well, thinking that it may have been the reason as to why there was an error

CodePudding user response:

The MM in "MM/dd/yyyy" means the month component will be padded with a 0, if necessary, to make it two digits long. Your input, "9/22/2017", uses only a single-digit month and so doesn't match that format. If you change the format to "M/dd/yyyy" it parses successfully.

Also, you don't need to truncate the time portion yourself; if the time format is consistent (HH : mm) then just parse it and use the Date property to get a DateTime for midnight of the same day...

DateTime dateSpec = DateTime.ParseExact(str[10], "M/dd/yyyy HH:mm", CultureInfo.CurrentCulture);
if (dateSpec.Date >= FromDate.Value && dateSpec.Date <= ToDate.Value) 
{ 
    //Do Something
}

Depending on how str is populated (e.g. user input) also consider using DateTime.TryParseExact(), which returns false upon failure rather than throwing a FormatException...

if (DateTime.TryParseExact(str[10], "M/dd/yyyy HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateSpec))
{
    // Handle parsing success

    if (dateSpec.Date >= FromDate.Value && dateSpec.Date <= ToDate.Value) 
    { 
        //Do Something
    }
}
else
{
    // Handle parsing failure
}

dateSpec is declared at the point it is passed as an out parameter, which is possible since C# 7.0.

CodePudding user response:

I managed to get it working by adding this block of code from another coder's suggestion on another platform

string[] formats = { "M/d/yyyy HH:mm", "M/dd/yyyy HH:mm", "MM/d/yyyy HH:mm", "MM/dd/yyyy HH:mm" };
DateTime dateSpec = DateTime.Now;
if (DateTime.TryParseExact(str[10].ToString(), formats, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateSpec))
{
    if (dateSpec.Date >= FromDate.Value.Date && dateSpec.Date <= ToDate.Value.Date)
        {
            //Do Something
        }
}
else
{
    MessageBox.Show("Error");
}
  • Related