0

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 ?

9
  • If your input is a string, you should also validate the string representation format. Prefer TryParseExact over ParseExact to avoid the exception Commented Nov 16, 2020 at 11:09
  • don't understand why you need to change culture of thread for this. What error will you get if you ignore this ? Commented Nov 16, 2020 at 11:13
  • Looks like you should be using h rather than hh: hh expects the hour as 2 digits i.e. 01 - 12, whereas your string is simply 3. Commented Nov 16, 2020 at 11:14
  • This error has nothing to do with ASP.NET Core or even .NET Core, in fact there are a lot of duplicate questions already. The string doesn't match the US format requested by using InvariantCulture. The fix is to not use strings in the first place. Commented Nov 16, 2020 at 11:18
  • @ZoharPeled now i am getting false my code is .. if (DateTime.TryParseExact(value as string, "MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) Commented Nov 16, 2020 at 11:18

1 Answer 1

2

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.

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

Comments

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.