0

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?

RobG
  • 142,382
  • 31
  • 172
  • 209
Curtis Crentsil
  • 459
  • 6
  • 20
  • Use [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString/) or one of these libraries: [moment.js](https://momentjs.com/docs/), [luxon](https://moment.github.io/luxon/index.html#/?id=luxon), [day.js](https://day.js.org/en/) – Wernfried Domscheit Nov 13 '22 at 12:00

2 Answers2

0
> 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>
-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}`))
Ping
  • 891
  • 1
  • 2
  • 10
  • `new Date(\`${yyyy}-${mmm}-${dd} ${time}\`)` returns an invalid date in Safari at least. Parsing unsupported timestamp formats with the built–in parser should be strongly discouraged. – RobG Nov 13 '22 at 10:59
  • Why reinvent the wheel? There are many ready-to-use libraries available for such tasks, e.g. [moment.js](https://momentjs.com/docs/), [luxon](https://moment.github.io/luxon/index.html#/?id=luxon) or [day.js](https://day.js.org/en/) – Wernfried Domscheit Nov 13 '22 at 11:57
  • This returns `2022-Nov-13 5:51:00` - which is not the desired output. – Wernfried Domscheit Nov 13 '22 at 11:58
  • if that is the case, maybe build an array for matching up the month format? – Ping Nov 13 '22 at 12:41