skip to Main Content

I have a date string of format ‘dd-mm-yyyy’ which I want to convert to Milliseconds.

let split_date = '31-01-2024'.split('-');
let d = new Date(parseInt(split_date[2]), parseInt(split_date[1]), parseInt(split_date[0]), 0, 0, 0, 0).getTime();
console.log(d);

let split_date2 = '02-02-2024'.split('-');
let d2 = new Date(parseInt(split_date2[2]), parseInt(split_date2[1]), parseInt(split_date2[0]), 0, 0, 0, 0).getTime();
console.log(d2);

This gives me output of 1709317800000 which seems to be incorrect. Also I get same milliseconds value for ’02-02-2024′.

Why is the milliseconds value incorrect and same for multiple dates?

2

Answers


  1. When using the Date constructor with several arguments, the month should be given between 0 and 11 (not between 1 and 12). So you should remove 1 from the month component and it will work.

    Login or Signup to reply.
  2. In the new Date(year, month, day) constructor, the month is 0-based. Ie January = 0, February = 1, and so on an so forth. See the docs

    So, new Date(2024, 1, 31) actually tries to create the 31st of February, which of course doesn’t exist. With the interal overflow logic, this results in the 2nd of March (because 2024 is a leap year, it would be the 3rd of March in a non leap year)

    And of course, applying your code on 02-02-2024 will call new Date(2024, 2, 2) which is — following the Date object’s internal logic — also the 2nd of March …

    See also this snippet of just creating the dates with the parameters you pass in

    console.log(new Date(2024, 1, 31, 12));
    console.log(new Date(2024, 2, 2, 12))

    So to fix your code, you have to substact 1 from the parsed month.

    let split_date = '31-01-2024'.split('-');
    let d = new Date(parseInt(split_date[2]), parseInt(split_date[1]) - 1, parseInt(split_date[0]), 0, 0, 0, 0).getTime();
    console.log(d);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search