Home > Mobile >  The problem of getting and working with dates in Js
The problem of getting and working with dates in Js

Time:09-22

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?

CodePudding user response:

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

CodePudding user response:

You can use moment.js to parse custom date formats just as in for example Java: https://momentjs.com/docs/#/parsing/string-format/

After that you can simply convert it to a js date using the toDate function: https://momentjs.com/docs/#/displaying/as-javascript-date/

Edit Example:

var mDate = moment('2022-09-21 10:15:00', 'YYYY-MM-DD HH:mm:ss');
var jsDate = mDate.toDate();
  • Related