-2

I would like to get today's date with the format below in React:

    "2019020420"

I am able to get the current date with this function. How do I modify this such that it will give me the above date format?

     getCurrentDate() {    
            var tempDate = new Date();
            var date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds();
            const currDate = date;
            return currDate;       
        }
cyber-leech
  • 37
  • 2
  • 2
  • 9
Baba
  • 2,059
  • 8
  • 48
  • 81

3 Answers3

0

try this library for formatting date in your desired format. https://date-fns.org/

Irfan Alam
  • 311
  • 1
  • 9
0

You can use template literals.

let formatTwoDigits = (digit) => ("0" + digit).slice(-2);
var tempDate = new Date();
var date = `${tempDate.getFullYear()}${formatTwoDigits(tempDate.getMonth()+1)}${formatTwoDigits(tempDate.getDate())}${formatTwoDigits(tempDate.getHours())}${formatTwoDigits(tempDate.getMinutes())}${formatTwoDigits(tempDate.getSeconds())}`;
console.log(date);

However, implementing date formatting by ourselves sometimes could be tedious. If you don't mind using a library, you can take a look at moment.js and its format functions. Moment.js is a commonly used JS library for parsing, manipulating, and formatting dates.

dekauliya
  • 1,303
  • 2
  • 15
  • 26
0

use moment.js from https://momentjs.com/ Take a look at there first few examples for how to use it for reformatting dates.

Joey Nelson
  • 335
  • 2
  • 7