How to Get Current Date and Time in React?

By Hardik Savani September 6, 2020 Category : React JS

This article is focused on how to display current date and time in react. i would like to share with you react native get current date and time. step by step explain get current date in react js. i would like to share with you get current time in react js.

Here, i will give you very simple examples of how to get current date and time in react app. we will use Date() to get current timestamps and then display date and time in react js app. you can as listed example i will want to share with you.

1) React Get Current Date Time

2) React Get Current Date (Y-m-d)

3) React Get Current Month

4) React Get Current Year

5) React Get Current Time (H:i:s)

You can simply check one by one example and pick as you need anyone.

1) React Get Current Date Time

import React, { Component } from 'react';

import { render } from 'react-dom';

class App extends Component {

constructor() {

this.state = {

currentDateTime: Date().toLocaleString()

}

}

render() {

return (

<div>

<p>

{ this.state.currentDateTime }

</p>

</div>

);

}

}

render(<App />, document.getElementById('root'));

Output:

Sun May 24 2020 09:59:56 GMT+0530 (India Standard Time)

2) React Get Current Date (Y-m-d)

import React, { Component } from 'react';

import { render } from 'react-dom';

class App extends Component {

constructor() {

var today = new Date(),

date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();

this.state = {

currentDate: date

}

}

render() {

return (

<div>

<p>

{ this.state.currentDate }

</p>

</div>

);

}

}

render(<App />, document.getElementById('root'));

Output:

2020-5-24

3) React Get Current Month

import React, { Component } from 'react';

import { render } from 'react-dom';

class App extends Component {

constructor() {

this.state = {

currentMonth: new Date().getMonth()

}

}

render() {

return (

<div>

<p>

{ this.state.currentMonth }

</p>

</div>

);

}

}

render(<App />, document.getElementById('root'));

Output:

4

4) React Get Current Year

import React, { Component } from 'react';

import { render } from 'react-dom';

class App extends Component {

constructor() {

this.state = {

currentYear: new Date().getFullYear()

}

}

render() {

return (

<div>

<p>

{ this.state.currentYear }

</p>

</div>

);

}

}

render(<App />, document.getElementById('root'));

Output:

2020

5) React Get Current Time (H:i:s)

import React, { Component } from 'react';

import { render } from 'react-dom';

class App extends Component {

constructor() {

var today = new Date(),

time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();

this.state = {

currentTime: time

}

}

render() {

return (

<div>

<p>

{ this.state.currentTime }

</p>

</div>

);

}

}

render(<App />, document.getElementById('root'));

Output:

11:2:54

I hope it can help you...

Tags :
Shares