The problem of getting and working with dates in Js

Viewed 48

When working with the task, it became necessary to get dates from html, and to find out the time difference between them:

var now_time_div = document.getElementById("time_now_of");
var start_time_div = document.getElementById("time_when_start_of");

var time_now = now_time_div.textContent || now_time_div.innerHTML;
var time_start = start_time_div.textContent || start_time_div.innerHTML;

After that, without thinking about the format of the data, I wanted to find the time difference in ms:

var worked_time = time_now - time_start

That didn't work, because we are working with a string. After entering the directory, I found the Date.parse() function, which returns the amount of time that has passed since the given date:

var worked_time = Date.parse(time_start);

but it turned out that it works only with a correctly submitted strig, for example We need to have:

Date.parse('01 Jan 1970 00:00:00 GMT');

We have:

Date.parse('21.09.2022, 15:34:21')

Maybe someone knows an easy way to implement this without rebuilding the string?

2 Answers

If you don't want to bring in a library like moment.js, you can just massage the date string a bit so it can be parsed correctly

const dateString = '21.09.2022, 15:34:21';
const curDate = dateString.split(',')[0].substring(0, 10).split('.');
const curTime = dateString.split(',')[1];
const parsed = `${curDate[1]}'/'${curDate[0]}'/'${curDate[2]} ${curTime}`;
console.log(new Date(parsed).toString()); // Properly formatted date

You can used this parsed variable to compare to other properly formatted dates

Related