Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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";


What I have tried:

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
Posted
Updated 7-Apr-22 21:47pm

Do NOT split string into parts! Use exact formats!

Try to use DateTime.TryParseExact Method (System) | Microsoft Docs[^]

See:
C#
string str10 = "9/22/2017 18:24";
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(str10, formats, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateSpec))
  //process your date
else
  //problem in datetime conversion
 
Share this answer
 
v3
"MM/dd/yyyy" is a very specific date format: it matches only 2 character months (01 to 12) and two character day of months (01 to 31).
To match months or days that may or may not have a leading aero, use the shorter date form "M/d/yyyy"

This may help in future: Formatting a DateTime for display - format string description[^] - the format strings are the same for input and output.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900