skip to Main Content

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


  1. Since you use angular you can also use the datePipe. This would also be my recommended approach.

     {{ youdate | date:'y/MM/d' }}
    

    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 and getDate returns a number between 1 and 31

    const d = new Date();
    
    const toFormat = (d) => {
      return `${d.getFullYear()}/${(d.getMonth()+1).toString().padStart(2, '0')}/${d.getDate().toString().padStart(2, '0')}`
    }
    
    console.log(toFormat(d));
    Login or Signup to reply.
  2. The 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

    let dateVar = 'Thu Jan 01 1970 01:00:00 GMT+010');
    let converted = new Date(dateVar).toLocaleDateString('sv-SE');
    

    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 "/".

    let dateVar = 'Thu Jan 01 1970 01:00:00 GMT+010');
    let converted = new Date(dateVar).toLocaleDateString('sv-SE')
    .replaceAll('-','/');
    

    Note: This does not change the time zone to Sweden, just the format of the date.

    Login or Signup to reply.
  3. 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:

    • take first 10 characters of the ISO string
    • replace all - with /
    function formatDate(date) {
        return date.toISOString().substring(0, 10).replaceAll('-', '/');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search