-1

I am trying to have the good format for the date : dd/MM/yyyy. Now I get 1606348737089 instead of the format dd/MM/yyyy. Here is my code :

import React, { useState, useEffect } from 'react'; 
  function App() {
    const [date, setdate] = useState(Date.now())
    return (
      <div>
        <p>{date}</p>
      </div>
    );
  }

export default App;

Here is my code : https://codesandbox.io/s/nostalgic-engelbart-tzbxv?file=/src/App.js

Do you know how can I do this ?

Thank you very much !

Peter
  • 105
  • 3
  • 10
  • Date.now() returns a [millisecond timestamp since the epoch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now). – Jared Smith Nov 26 '20 at 00:14
  • If you don't mind inlcuding another library, you could just use [moment.js](https://momentjs.com/) and do whatever format you want. – kman Nov 26 '20 at 00:23
  • Hi Peter, just a quick heads up. Welcome to Stack Overflow. You haven't been accepting any answers for your past questions. Please see, [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) Also go through the [tour] so that you will be familiar with how to use this platform. – Praveen Kumar Purushothaman Nov 26 '20 at 06:12

2 Answers2

0

You can make an function like below and pass the state value as parameter and just call the function in your render method ;)

function formattedDate(stateValue = new Date) {
  let month = String(stateValue.getMonth() + 1);
  let day = String(stateValue.getDate());
  const year = String(stateValue.getFullYear());

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

  return `${day}/${month}/${year}`;
}
0

You can use a lightweight date library like dayjs to format your date:

import React, { useState, useEffect } from 'react';
import dayjs from 'dayjs';

  function App() {
    const [date, setdate] = useState(Date.now())
    return (
      <div>
        <p>{dayjs(date).format('DD/MM/YYYY')}</p>
      </div>
    );
  }

export default App;