Home > OS >  how to convert sting date to normal date format in js
how to convert sting date to normal date format in js

Time:11-13

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?

CodePudding user response:

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}`))

CodePudding user response:

You can try using moment,

Here is the doc: https://momentjs.com/

CodePudding user response:

> 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>
  • Related