Skip to content
Advertisement

Subtraction of dates in seconds in JavaScript

I have a form with mathematical operations, the user has the right to select two dates and perform a subtraction operation. To do this, I need to translate each date into seconds and read the seconds.

I cant get seconds with date format like this

let date_first = rowNode.data[val[0]]; // 16.02.2021 04:20:55
let date_second = rowNode.data[val[1]]; // 16.02.2021 02:45:35
if (date_first == null || date_second == null) {
  date_first = 0;
  date_second = 0;
}
let get_date_first = Date.parse(new Date(date_first)); // NOTHING
let get_date_second = Date.parse(new Date(date_second)); // NOTHING
rowNode.data[unique_id] = (get_date_first - get_date_second) / 1000;

Advertisement

Answer

Convert the invalid date string on the server or like this

const getDate = str => new Date(str.replace(/(d{2}).(d{2}).(d{4})(.*)/,"$2/$1/$3$4"));

const d1 = getDate("16.02.2021 04:20:55")
const d2 = getDate("16.02.2021 02:20:55")
console.log(Math.floor((d1.getTime()-d2.getTime())/1000))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement