I’m working on an Angular web app that has a date field form that uses angular material datepicker.
When the user selects a date with the datepicker, the value of the date I retrieve is in the format:
Thu Jan 01 1970 01:00:00 GMT+010
, I would like to convert into yyyy/mm/dd
Are there any built function to convert?
3
Answers
Since you use angular you can also use the datePipe. This would also be my recommended approach.
Otherwise you can do it like so using the date object, however I recommend a lib like dayjs which provides a
format
function.Note that
getMonth
is 0 based andgetDate
returns a number between 1 and 31The question is if you are actually receiving that as a string or as a date object (they usually look like that when console.logged).
But anyway you should be able to convert using either Intl.DateTimeFormat, or more conveniently the Date method toLocaleDateString
Here I chose ‘Swedish’ (sv) and location Sweden (SE) with gives "1970-01-01". I don’t know if there is a country that has "1970/01/01" as standard. If not just keep Sweden as above and replace "-" with "/".
Note: This does not change the time zone to Sweden, just the format of the date.
Alternatively, you can leverage ISO string which is always the same format
YYYY-MM-DDTHH:mm:ss.sssZ
In order to format it as
YYYY/MM/DD
you simply:-
with/