0

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?

  • ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) is the only date format explicitly specified to be supported, though most browsers seem to support a wide range of alternatives. Question: What is the source of the dates in the html, i.e., is this is user input or generated by the server or a script? – Yogi Sep 21 '22 at 13:11
  • It is generated on the site with which the program should work – Ivan Mishakivskiy Sep 21 '22 at 13:16
  • @yogi—there are [two others](https://262.ecma-international.org/13.0/#sec-date.parse): the formats produced by *toString* and *toUTCString*. ;-) – RobG Sep 22 '22 at 07:56

2 Answers2

1

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

tuckermassad
  • 126
  • 4
  • This substitutes one unsupported format with another. If you’re going to parse the string, do it properly and either generate a supported format or pass the values for year, month, day, etc. directly to the constructor (which is preferable to parsing twice). – RobG Sep 22 '22 at 07:59
0

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();
Jalau
  • 303
  • 1
  • 2
  • 11