mardi 26 juillet 2016

convert various date formats to yyyy-mm-dd in javascript

I want to be able to convert various date formats to a single format, i.e.to yyyy-mm-dd , so for example:

20-10-1975 -> 1975-10-20 (dd-mm-yyyy -> yyyy-mm-dd) 

01-25-1961 ->1961-01-25 (mm-dd-yyyy -> yyyy-mm-dd) 

1991-10-25 -> 1991-10-25 (yyyy-mm-dd remains yyyy-mm-dd)

if possible also with the time component, so for example:

20-10-1975 13:15:22 -> 1975-10-20 13:15:22

The reason is I want to be able to sort an array on dates, but sometimes I have to deal with various formats which I don't control.

Is there a function to achieve this?

PS I am aware that sometime a date can be ambiguous, for example 6-5-2015 can be 6th of May, or 5th of June, but I am fine with this as long as the sorting works.

Aucun commentaire:

Enregistrer un commentaire