0

I am trying to create a small program where I have to display date and time using react JS. It is displaying everything as expected except date and time value in the HTML page.

enter code here
import React from "react";
import ReactDOM from "react-dom";

const name = "Flash";
const currDate = new Date().toLocaleDateString;
const currTime = new Date().toLocaleTimeString;

ReactDOM.render(
<>
<h1>My name is {name}</h1>
<p> Current Date is = {currDate} </p>
<p> Curremt Time is = {currTime} </p> 
</>,
document.getElementById("root"));
  • Your answer is here https://stackoverflow.com/questions/10599148/how-do-i-get-the-current-time-only-in-javascript – Monzoor Tamal Jul 26 '20 at 20:19
  • Please clarify the actual result versus what you are expecting. It is displaying null, undefined, some other result you were not expecting? – dikuw Jul 26 '20 at 21:28

2 Answers2

3

Everything is perfect in your code, but you just forgot to run these functions.

toLocaleDateString and toLocaleTimeString are functions not just objects so you need to add parenthesis to run these functions and get the results.

so replace this:

const currDate = new Date().toLocaleDateString;
const currTime = new Date().toLocaleTimeString;

with this:-

const currDate = new Date().toLocaleDateString();
const currTime = new Date().toLocaleTimeString();

So your final code becomes this:-

import React from "react";
import ReactDOM from "react-dom";

const name = "Flash";
const currDate = new Date().toLocaleDateString();
const currTime = new Date().toLocaleTimeString();

ReactDOM.render(
<>
<h1>My name is {name}</h1>
<p> Current Date is = {currDate} </p>
<p> Curremt Time is = {currTime} </p> 
</>,
document.getElementById("root"));
Kashan Haider
  • 1,036
  • 1
  • 13
  • 23
0

A simple step by step guide to get current date in Reactjs

import React from 'react';
import logo from './logo.svg';
import './App.css';

class App extends React.Component {
  state={
    curTime : new Date().toLocaleString(),
  }
  render(){
    return (
      <div className="App">
        <p>Current Time : {this.state.curTime}</p>
      </div>
    );
  }
}

export default App;
Momin
  • 3,200
  • 3
  • 30
  • 48