My problem is the following:
I have a var in javascript that represents a date in the following format in the following format ‘dd/mm/yyyy’
so, if I have 01/03/2024, this would be 1st of March, 2024
I am trying to manipulate this, my problem:
var test = "01/03/2024";
if I create avar myDate = new Date(test);
and I see what’s inside myDate it will point to the 3rd of January, 2024.
Is there any way to format the date when creating a new Date object?
I explored with moment.js but it’s erroring somewhere
I tried the following var myDate=moment(test, ‘dd/mm/yyyy’).toDate();
but it errors when trying to manipulate myDate at a later stage.
2
Answers
I suggest using
day.js
since it is a tiny library that can fulfill your requirements. Alsomoment.js
is get deprecated.All you need to do is breaking down in 2 steps.
Add the library
In order to make day.js available to your code, you need to load it. So in a
<head>
section of your page you can add the following:Start using it
Here is a simple example from your question:
Here is a list of useful links for more examples:
Split and reverse the string with ‘-‘ and attach ‘T00:00:00’ and pass to the Date’s constructor: