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
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:
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.
You can use moment.js package:
And use:
or
Like this:
Documentation: https://momentjs.com/
The
Uncaught RangeError: Invalid time value
error occurs because thetoLocaleDateString()
method returns the date in the formatdd/mm/yyyy
, which is not a valid input for creating a JavaScript Date object directly. To set the initial value ofstartDate
as a string in the format2/08/2023
, you can manually format the date using thegetFullYear()
,getMonth()
, andgetDate()
methods of the Date object.Here’s how you can achieve that:
In this code, we first create a new Date object and then manually construct the desired date string in the format
dd/mm/yyyy
. ThegetMonth()
method returns a value from 0 to 11, where 0 represents January, 1 represents February, and so on. Hence, we add 1 to thegetMonth()
value to get the correct month number.This should set the initial value of
startDate
to today’s date in the format2/08/2023
.