How to convert 2021-07-14T00:00:00.000Z into a standard date in YYYY-MM-DD format

Viewed 14677

Can someone please explain how to convert this 2021-07-14T00:00:00.000Z date string value into the YYYY-MM-DD format in react.js (javascript)

4 Answers

You can simply use moment.js

  1. install moment.js package by simply typing this in your terminal

    npm install moment --save

2.Import moment file into your respective .js file

import moment from "moment";

3.You can simply use the folowing code to convert

moment("2021-07-14T00:00:00.000Z").utc().format('YYYY-MM-DD')

or

console.log(moment("2021-07-14T00:00:00.000Z").utc().format('YYYY-MM-DD'));

and the output will be

2021-07-14

A great blog

https://blog.stevenlevithan.com/archives/date-time-format

wanted format : YYYY-MM-DD

using :

  1. internal script
  2. external script
    <!DOCTYPE html>
    <html>
    <body>

    <!--... external javascript ...-->
    <script type="text/javascript" src="https://stevenlevithan.com/assets/misc/date.format.js"></script>

    <h2>JavaScript new Date() - YYYY-MM-DD </h2>
    <p id="demo1"></p>
    <p id="demo2"></p>
    <p id="demo3"></p>
    
    <script>
    const d1 = new Date("2021-07-14T00:00:00.000Z")

    // 01 - input
    document.getElementById("demo1").innerHTML = d1;

    function formatDate(date) {
      var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

      if (month.length < 2) 
        month = '0' + month;
      if (day.length < 2) 
        day = '0' + day;

      return [year, month, day].join('-');
    }

    // 02 - using function formatDate
    var result2 = formatDate(d1);

    console.log(result2);
    document.getElementById("demo2").innerHTML = result2;

    // 03 - external javascript 
    var result3 =d1.format("yyyy/mm/dd");
    document.getElementById("demo3").innerHTML = result3;

    </script>

    </body>
    </html>

OUTPUT :

Wed Jul 14 2021 02:00:00 GMT+0200 (Central European Summer Time)
2021-07-14
2021-07-14

You can use date formatting packages like dayjs, moment.js or strftime

You can use datefns. import {format} from 'date-fns'; format(new Date(pass your isostring), 'p, dd/MM/YYYY');

Related