skip to Main Content

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


  1. I suggest using day.js since it is a tiny library that can fulfill your requirements. Also moment.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:

    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
    

    Start using it

    Here is a simple example from your question:

    var test = "01/03/2024"
    var myDate = new Date(test);
    console.log(dayjs(myDate).format('DD/MM/YYYY'));
    

    Here is a list of useful links for more examples:

    Login or Signup to reply.
  2. Split and reverse the string with ‘-‘ and attach ‘T00:00:00’ and pass to the Date’s constructor:

    const date = new Date('01/03/2024'.split('/').reverse().join('-') + 'T00:00:00');
    
    console.log(date.toLocaleString());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search