Reputation: 167
when i try to convert string to date following exception occured
FormatException: String '11/17/2020 3:23 PM' was not recognized as a valid DateTime.
my code is ...
public class PaperDTO
{
...
[DeadLineValidate(maxday: 62, ErrorMessage = "please specify valid date maximum 62 days are valid")]
public string DeadLine { get; set; }
...
}
public class DeadLineValidate : ValidationAttribute
{
public DeadLineValidate(int maxday){ Maxday = maxday; }
public int Maxday { get; }
public override bool IsValid(object value)
{
var date = DateTime.ParseExact(value as string, "MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture);
return DateTime.Today <= date && date <= DateTime.Today.AddDays(Maxday);
}
}
if i use in my action method...
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
then it works fine but in this approach i have to change culture of thread just for date conversion and unnecessarily i have to write extra code in action method of controller
does anyone have any idea regarding this ?
Upvotes: 0
Views: 442
Reputation: 24147
Your date pattern requires 2 digits for the hour, but your value has only 1 digit. Try this date pattern instead, it will support both 1 and 2 digits:
"MM/dd/yyyy h:mm tt"
Note that the same issue (and the same solution) might apply for the Month and Day values.
Upvotes: 2