skip to Main Content

I just want todays date in string format(eg 2/08/2023 ) inside a usestate hook variable as a initial value.

Current working code

const [startDate, setStartDate] = useState(new Date());

// output Wed Aug 02 2023 12:52:16 GMT+0800 (Australian Western Standard Time)

what i have tried for outputing (2/08/2023)

Trial 1 
--------
const [startDate, setStartDate] = useState(new Date().toLocaleDateString());


Trial 2 
--------

let today = new Date().toLocaleDateString()
const [startDate, setStartDate] = useState(today)

Both gives me a error

Uncaught RangeError: Invalid time value. Any way to fix this ??

Thank you !

3

Answers


  1. The RangeError: Invalid time value error occurs because the toLocaleDateString() method returns a string in the format ‘M/D/YYYY’ (e.g., ‘8/2/2023’), and when you pass this string to the useState hook, it tries to create a new Date object from that string, but it doesn’t recognize the format, resulting in the error.

    To fix this issue and store today’s date in the format ‘2/08/2023’ inside a useState hook variable, you can format the date manually before passing it to the hook. One way to achieve this is by creating a custom formatting function.

    Here’s how you can do it:

      const formatDate = (date) => {
      const day = date.getDate().toString().padStart(2, '0');
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const year = date.getFullYear();
      return `${day}/${month}/${year}`;
    };
    
    const today = new Date();
    const [startDate, setStartDate] = useState(formatDate(today));
    

    In this code, the formatDate function takes a Date object and returns a formatted date string in the ‘D/MM/YYYY’ format. It uses the getDate(), getMonth(), and getFullYear() methods to extract the day, month, and year components, respectively. The padStart method is used to ensure that the day and month components are always two digits.

    Now, the startDate variable will hold today’s date in the desired format (‘2/08/2023’) as the initial value.

    Login or Signup to reply.
  2. You can use moment.js package:

    npm i moment

    And use:

    moment().format('l'); // 8/2/2023
    

    or

    moment().format('L'); // 08/02/2023
    

    Like this:

     import "./styles.css";
    import moment from 'moment'
    import { useState } from "react";
    
    export default function App() {
      const [startDate, setStartDate] = useState(moment().format('L'));
      return (
        <div className="App">
          <h1>{startDate}</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }
    

    Documentation: https://momentjs.com/

    Login or Signup to reply.
  3. The Uncaught RangeError: Invalid time value error occurs because the toLocaleDateString() method returns the date in the format dd/mm/yyyy, which is not a valid input for creating a JavaScript Date object directly. To set the initial value of startDate as a string in the format 2/08/2023, you can manually format the date using the getFullYear(), getMonth(), and getDate() methods of the Date object.

    Here’s how you can achieve that:

    const currentDate = new Date();
    const formattedDate = `${currentDate.getDate()}/${currentDate.getMonth() + 1}/${currentDate.getFullYear()}`;
    
    const [startDate, setStartDate] = useState(formattedDate);
    

    In this code, we first create a new Date object and then manually construct the desired date string in the format dd/mm/yyyy. The getMonth() method returns a value from 0 to 11, where 0 represents January, 1 represents February, and so on. Hence, we add 1 to the getMonth() value to get the correct month number.

    This should set the initial value of startDate to today’s date in the format 2/08/2023.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search