skip to Main Content

I am using MongoDB to store data, and on retrieving them I want to get the date and convert it to something that looks like this:

'2022-07-20T10:12:21.054Z'

right now my date looks like this:

"Nov. 13, 2022 at 5:51 AM "

because I am getting it directly from mongo through the createdAt key. How can I achieve this?

2

Answers


  1. > Try this using moment library you can make any format you want.
    <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>Title</title>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
            </head>
            <body>
            
            <button type="button" onclick="clickHandler()">
                Get Today!
            </button>
            <script>
                function clickHandler() {
                    alert(moment('2022-07-20T10:12:21.054Z')
                        .format('MMM. , DD YYYY at h:mm:ss a'))
                }
            </script>
            </body>
        </html>
    
    Login or Signup to reply.
  2. Try this: (You may need to define your time zone to get this right)

    const dateStr = 'Nov. 13, 2022 at 5:51 AM'
    const regex = /.|,|s|:/g
    const dateArray = dateStr.split(regex);
    const ampmTo24hr = (hh,mm,ampm) => (
      ampm === 'AM' ?
        `${hh}:${mm}:00` :
        `${parseInt(hh,10) + 12}:${mm}:00`
      );
    
    const [mmm,,dd,,yyyy,,hh,mm,ampm] = dateArray;
    const time = ampmTo24hr(hh,mm,ampm);
      
    console.log(`${yyyy}-${mmm}-${dd} ${time}`)
    console.log(new Date(`${yyyy}-${mmm}-${dd} ${time}`))

    Looks like new Date(`${yyyy}-${mmm}-${dd} ${time}`) this format may not be supported, build an array for Month format matching or add a switch function could be a choice:

        const dateStr = 'Nov. 13, 2022 at 5:51 AM'
        const regex = /.|,|s|:/g
        const dateArray = dateStr.split(regex);
        const getMonth = (str) => {
          switch(str.toUpperCase()) {
            case 'JAN': return '01';
            case 'FEB': return '02';
            case 'MAR': return '03';
            case 'APL': return '04';
            case 'MAY': return '05';
            case 'JUN': return '06';
            case 'JUL': return '07';
            case 'AUG': return '08';
            case 'SEP': return '09';
            case 'OCT': return '10';
            case 'NOV': return '11';
            case 'DEC': return '12';
          }
        }
        const ampmTo24hr = (hh,mm,ampm) => (
          ampm === 'AM' ?
            `${hh}:${mm}:00` :
            `${parseInt(hh,10) + 12}:${mm}:00`
          );
    
        const [mmm,,dd,,yyyy,,hh,mm,ampm] = dateArray;
        const time = ampmTo24hr(hh,mm,ampm);
          
        console.log(new Date(`${yyyy}-${getMonth(mmm)}-${dd} ${time}`))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search