1

I'm trying to check if the 'date-time' string is ISO formatted and I get the following output:

isIsoDate the date string is not ISO format! :  2022-04-21T09:40:01.000Z
isIsoDate converted-back date :  2022-04-21T09:40:01.000Z
isIsoDate time stamp number :  1650534001000
isIsoDate string builded back :  Thu Apr 21 2022 11:40:01 GMT+0200 (Ora legale dell’Europa centrale) 

this is my code:

export function isIsoDate(dateString) {
    
        var dateParsedNum = Date.parse(dateString);
        var dateBackToString = new Date(dateParsedNum);
        var stringBuilded = "";
    
    
        stringBuilded = dateBackToString.toString()
    
    
        if ((dateBackToString.toString()) == dateString) {
            return true;
            
        } else {
           console.debug("isIsoDate() the date string is not ISO format! : ", dateString);
           console.debug("isIsoDate() converted-back date : ", dateBackToString);
           console.debug("isIsoDate() time stamp number : ", dateParsedNum);
           console.debug("isIsoDate() string builded back : ", stringBuilded);
           // throw new BadRequestException('Validation failed');
        }
    
        return(false)
    }
Salman A
  • 262,204
  • 82
  • 430
  • 521
philsax
  • 11
  • 1
  • 3
    Change `dateBackToString.toString()` to `dateBackToString.toISOString()`. That being said, this won't be enough (e.g. `+00:00` is changed to `Z`). – Salman A May 19 '22 at 13:35
  • I suppose you could replace `Z` with `+00:00` and then compare. Or use an `if` statement and make that comparison a special case. – Robert Harvey May 19 '22 at 13:38
  • ``` var dateParsedNum = Date.parse(dateString); var dateBackToString = new Date(dateParsedNum); var stringBuilded = ""; // stringBuilded = dateBackToString.toString() stringBuilded = dateBackToString.toISOString() The above is now working as expected, thanks – philsax May 20 '22 at 13:26

1 Answers1

1

I'm not sure if it can be done with JavaScript's Date utilities. As Salman said in the comments, you can have .toISOString() instead, but this method converts everything into UTC, whereas the ISO specification is more flexible than that.

I recommend this StackOverFlow answer that uses RegEx to validate ISO strings.

J Eti
  • 192
  • 4
  • 13