-3

Javascript how to check if the parameter is a date in object,

I got this object from backend

  "data": {
    "name": "tony",
    "gender": "F",
    "city": "taichuang",
    "date": "2019-09-28T08:00:00.000Z",
    "level": "3",
    "date2": "2019-12-04T00:00:00.000Z",
    "no": "11232",
    "color": "red"
  }

I use *ngFor to render this data, but I have to parse date format to yyyy-mm-dd, Every parameter is dynamic, so I don't know which parameter is date, How can I do?

ps.dev with angular9

Shaolin
  • 1
  • 4
  • You mean you use `ngFor` to render the data? – ruth Mar 23 '20 at 08:31
  • Do you mean how you can recognise which values represent dates (not really Angular specific, it's just JS)? If so, then if they are all ISO 8601 dates like you show here you could write a regex to match them. – jonrsharpe Mar 23 '20 at 08:33
  • yes I use ngFor, I need to parse every date to the format what I need. – Shaolin Mar 23 '20 at 08:36
  • Please do not post questions so SO can do your work for you. Even answers with valueable information are being downvoted just because they do not do everything for you. Shame – Gecko Mar 23 '20 at 08:43
  • This questions not Angular specific but rather JavaScript general. I suggest you remove Angular from title and tags. – Alexander Trakhimenok Mar 23 '20 at 08:43
  • Thanks for suggest, sorry about the bad question, I don't know how to explain my question. – Shaolin Mar 23 '20 at 08:50
  • If the property name starts with "date" it seems it's an ISO 8601 timestamp. Maybe you can do something like `dateProps = Object.keys(data).filter(prop => /^date/.test(prop))` to get an array of the date property names. To get the dates, tack `.map(prop => data[prop])` on the end. – RobG Mar 23 '20 at 11:23

1 Answers1

0

You can 1st check if a property is a string and then use regular expression to check if it satisfies required pattern.

You can use examples of patterns for example from answers to this question: javascript regex iso datetime

Alexander Trakhimenok
  • 6,019
  • 2
  • 27
  • 52