0

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

4
  • you miss the time part in "MM/dd/yyyy"? Commented Apr 8, 2022 at 7:33
  • but the thing is, I just wanted to filter it by date unless it is a must with the time as well? bc the array date[0] is just the date "9/22/2017" Commented Apr 8, 2022 at 7:35
  • Why are you using strings instead of DateTime object in the first place? If you absolutely have to use strings, use they ISO8601 format, YYYY-MM-DD. It's the only unambiguous format and is recognized by DateTime.Parse Commented Apr 8, 2022 at 8:14
  • Using string instead bc the data of the dates are in an excel file that I had imported into a listbox filtered with only the things i need to see (other data eg: name, etc..), so I wanted to filter it further Commented Apr 8, 2022 at 8:26

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am not sure as to why it still isn't working. I tried changing the format to M/d/yyyy H:mm because I looked back onto the list of dates that I have but it still has the same error as an invalid format
What input string(s) is it failing on? "9/22/2017 18:24" parses for me with "M/d/yyyy H:mm". Did you change the first argument passed to ParseExact() from date[0] to str[10]? What is the value of CultureInfo.CurrentCulture.DisplayName?
-2

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");
}

1 Comment

This is effectively the same as the second code snippet in my answer except you're passing (guessing at?) four formats instead of one. I have confirmed that, in the invariant and en-US cultures, M/d/yyyy HH:mm successfully parses all four combinations of one- and two-digit months and days; MM fails to parse a single-digit month (9) so your last 2, if not 3, formats here seem unnecessary. It's hard to see how this answer will be useful to anyone but yourself when you provided only one sample input and didn't respond to my clarifying questions in response to your comment on my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.