6

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)

5 Answers5

11

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
Mystica
  • 189
  • 10
3

You can use datefns.

import {format} from 'date-fns';
console.log(format(new Date("2021-07-14T00:00:00.000Z"), 'p, dd/MM/YYYY'));
Johnty
  • 246
  • 1
  • 2
  • 18
1

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
kris
  • 392
  • 4
  • 16
0

no need to use third party libraries, just use string slicing in JavaScript. here is the code

const dateString = '2023-08-01T12:48:50Z';
const indexOfT = dateString.indexOf('T');
const dateWithoutTime = dateString.substring(0, indexOfT);

console.log(dateWithoutTime); // Output: 2023-08-01
Anshu Meena
  • 169
  • 1
  • 6
0

2021-07-14T00:00:00.000Z is a Date string in the ISO format. You can just String#slice the first 10 characters in order to get the YYYY-MM-DD format.

const dateString = '2021-07-14T00:00:00.000Z';
const formattedDate = dateString.slice(0, 10);

console.log(formattedDate); // "2021-07-14"
Behemoth
  • 5,389
  • 4
  • 16
  • 40