Skip to Content

How do I get the date time in React?

How do I get the date time in React?

Knowing the current date and time is a common requirement in many web applications. React provides easy ways to get the current date and time in your components using JavaScript’s built-in Date API.

What is the Date API in JavaScript?

The Date API in JavaScript allows you to work with dates and times. The Date object represents a single moment in time. You can use the Date constructor to create Date objects. For example:


const now = new Date()

This creates a Date object representing the current date and time. Once you have a Date object, you can call methods on it to get the day, month, year, hours, minutes, seconds, and more.

Some common methods for getting date/time values are:

  • getFullYear() – Get the year as a four digit number (yyyy)
  • getMonth() – Get the month as a number (0-11)
  • getDate() – Get the day of the month (1-31)
  • getDay() – Get the day of the week as a number (0-6)
  • getHours() – Get the hour (0-23)
  • getMinutes() – Get the minutes (0-59)
  • getSeconds() – Get the seconds (0-59)

There are also methods like getTime() and valueOf() that return the date as a numeric timestamp value.

Getting the Current Date and Time

To get the current date and time in React, you simply need to create a new Date object and call the methods you need:


const now = new Date()

const year = now.getFullYear() // 2023 
const month = now.getMonth() + 1 // 10
const date = now.getDate() // 10
const hours = now.getHours() // 16 
const minutes = now.getMinutes() // 35

This gives you full access to the current date and time in your React component.

Displaying the Date and Time

Once you’ve obtained the date and time values, you can display them in your UI any way you like.

Here is an example component that displays the current date and time:


import React from 'react'

export default function DateTimeDisplay() {

  const now = new Date()

  const date = now.getDate()
  const month = now.getMonth() + 1
  const year = now.getFullYear()

  const hours = now.getHours()
  const minutes = now.getMinutes()

  return (
    <div>
      <p>{date}/{month}/{year}</p>  
      <p>{hours}:{minutes}</p>
    </div>
  )

}

This displays the date and time nicely formatted in JSX. You can customize the formatting and styling to your needs.

Updating in Real Time

The Date object always represents the current date and time. So if you want to display a clock that updates in real time, you need to call the Date methods inside a useEffect hook:


import { useState, useEffect } from 'react'

export default function Clock() {

  const [date, setDate] = useState(new Date());
  
  useEffect(() => {
    const timer = setInterval(() => setDate(new Date()), 1000 )
    return function cleanup() {
      clearInterval(timer)
    }

  }, [])

  return (
    <div>
      <p>{date.toLocaleTimeString()}</p>
    </div>
  )

} 

This will update the current time every second, keeping the display up to date.

Formatting the Date and Time

When displaying dates and times, you typically want to format them in a human readable way. Here are some common ways to format dates and times in React:

Formatting Dates


// March 5, 2023
date.toDateString() 

// 03/05/2023
date.toLocaleDateString()

Formatting Times


// 10:30:15 PM 
date.toLocaleTimeString()

Using External Libraries

For more robust formatting, you can use libraries like:

  • date-fns
  • Moment.js

These provide functions for formatting dates and times with full localization support.

For example with date-fns:


import { format } from 'date-fns'

format(date, 'MMMM dd, yyyy HH:mm') // March 05, 2023 22:30 

Validating Date Input

When getting date/time input from users, the input needs to be validated and converted to a valid Date object. Here are some ways to handle date input validation in React:

1. Check against min/max


const minDate = new Date(2020, 0, 1) // Jan 1st, 2020
const maxDate = new Date() // today

if (userDate >= minDate && userDate 

2. Compare against ranges


function isValidDate(userDate) {
  const today = new Date()
  return (userDate > today.setFullYear(today.getFullYear() - 18) && userDate 

3. Validate formatting


function isValidFormat(dateString) {
  const regex = /^\d{2}\/\d{2}\/\d{4}$/ // MM/dd/yyyy
  return regex.test(dateString) 
}

4. Convert to Date object


function convertToDate(dateString) {
  const date = new Date(dateString)
  return isNaN(date) ? null : date
}

This will return null if dateString can't be parsed to a valid date.

Common Issues and Solutions

Here are some common issues faced when working with dates/times in React and how to solve them:

Times are Off by UTC Offset

Date objects are UTC by default. To offset to local timezone, set timezone offset:


const offset = date.getTimezoneOffset() * 60 * 1000 

date = new Date(date.getTime() + offset)

Comparing Dates Doesn't Work

Always convert dates to timestamps before comparing:


const date1 = new Date('March 5 2022')
const date2 = new Date('January 1 2022')

date1.getTime() > date2.getTime() // true

Formatting is Localized Incorrectly

Pass locale to toLocaleString() or use a library like date-fns with locale support.

Dates Don't Persist When Navigating

Store dates in state management like Redux or write to localStorage.

Issues with Timezones

Use a library like Moment.js or Luxon that handles timezones cleanly.

Conclusion

Working with dates and times is tricky, but React provides easy access to JavaScript's built-in Date API for handling most use cases.

The key things to remember are:

  • Create Date objects to represent dates/times
  • Extract values using Date getter methods
  • Format dates/times for display with toLocaleString() or external libraries
  • Validate and sanitize any user provided dates
  • Use appropriate state management for persisting DateTime values

With the power and flexibility of the JavaScript Date object, you can handle all kinds of date and time requirements in your React applications.