Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate check datetime input as ISO 8601

I try to validate an input and then i can get input like that i want to.

Example:

if (string != validate(string)) 
       then not valid
else 
       then valid

Inputs and expected output

2017-03-17T09:44:18.000+07:00 == valid

2017-03-17 09:44:18 == not valid
like image 340
Christopher Avatar asked Sep 05 '25 03:09

Christopher


1 Answers

To check valid DateTime, you need correct DateTime format (i.e "yyyy-MM-ddTHH:mm:ss.fffzzz") and use DateTime.TryParseExact() to validate your datetime string,

Try below code to validate your datetime string,

 public void ValidateDateTimeString(string datetime)
 {
        DateTime result = new DateTime(); //If Parsing succeed, it will store date in result variable.
        if(DateTime.TryParseExact(datetime, "yyyy-MM-ddTHH:mm:ss.fffzzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
            Console.WriteLine("Valid date String");
        else
            Console.WriteLine("Invalid date string");
 }

Try it online

like image 176
Prasad Telkikar Avatar answered Sep 07 '25 22:09

Prasad Telkikar