Get Current Date and Time using ReactJs

Get Current Date and Time using ReactJs

In this tutorial we have provided four different examples to get current date and time using ReactJs.

First Example

In this example we will simply display current date and time using ReactJs by making a common utility function.


export function getCurrentDate(separator=''){

let myCurrentDate = new Date()
let date = myCurrentDate.getDate();
let month = myCurrentDate.getMonth() + 1;
let year = myCurrentDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

Second Example

In the second example native JavaScript date function is used to get current date and time in ReactJs.

body
<script>
function MyFunction() {
var myCurrentDate = new Date();
var date = myCurrentDate.getFullYear() + '-' + (myCurrentDate.getMonth()+1) + '-' + myCurrentDate.getDate() +' '+ myCurrentDate.getHours()+':'+ myCurrentDate.getMinutes()+':'+ myCurrentDate.getSeconds();
const newCurrentDate = "Current Date and Time: "+date;
return (
<p>{newCurrentDate}</p>
);
}
ReactDOM.render(
<MyFunction />,
document.getElementById('root')
);
</script>

Output

The output will be in this format YYYY-MM-DD H:MM:SS.

Current Date and Time: 2020-09-25 4-23-55

Third Example

In this example new Date() is again used to get current date and time using ReactJs.


import React from 'react';

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

export default App;

Demo

Current Date and Time: 21/02/2020, 04:23:55

Using react-moment Package

You can also use react-moment Package to get the current date and time in reactJs.


import moment from "moment";
date_create: moment().format("DD-MM-YYYY hh:mm:ss")

Post a Comment

Previous Post Next Post