Я пытаюсь вычесть два раза друг от друга и по большей части работает, но в некоторых сценариях он дает неправильный вывод.Вычитание даты времени в формате UTC в Javascript
Вот мой код до сих пор:
//postDateTime looks like 2015-04-23T22:23:32.902Z
//Split the date and time
var postDateTime2 = postDateTime.split("T");
//remove the Z from the post time stamp
postDateTime2[1] = postDateTime2[1].replace('Z','');
//split the post date/time into sperate variables
var postDate = postDateTime2[0]; // date
var postTime = postDateTime2[1]; // time
//split up the post time into hours, minutes, seconds
var postTimeSplit = postTime.split(":");
var postTimeHour = postTimeSplit[0];
var postTimeMinutes = postTimeSplit[1];
var postTimeSeconds = postTimeSplit[2];
//split the date to have year, month, date separate
var postDateSplit = postDate.split("-");
//split the post date to year, month, date
var postYear = postDateSplit[0]; //year
var postMonth = postDateSplit[1]; //month
var postDate2 = postDateSplit[2]; //date
//get the current hour, minutes, seconds in UTC time.
var hours = now.getUTCHours();
var minutes2 = now.getUTCMinutes();
var seconds2 = now.getUTCSeconds();
//get the difference in years between post time and response time
var responseYear = Math.abs(now.getUTCFullYear() - postYear);
//get the difference in months between post time and response time
var responseMonth = Math.abs(mm - postMonth);
//get the difference in days between post time and response time
var responseDate = Math.abs(now.getUTCDate() - postDate2);
//get the difference in hours between post time and response time
var responseHour = Math.abs(now.getUTCHours() - postTimeHour);
//get the difference in minutes between post time and response time
var responseMinutes = Math.abs(now.getUTCMinutes() - postTimeMinutes);
//get the difference in seconds between post time and response time
var responseSeconds = Math.abs(now.getUTCSeconds() - postTimeSeconds);
Math.round(responseSeconds); // round the seconds to up to 2 decimal (doesn't work as expected)
Так как я уже сказал, это работает, но если разница во времени больше, чем один час, это начинает давать странные выходы. Например, если разница в режиме реального времени составляла всего 38 минут, а текущее время на час вперед, оно будет считать это 1 час 22 минуты.
Любые предложения, как я могу сделать это лучше?
Чтобы дать лучшее объяснение проблемы, посмотрите на этот пример: 2015-04-23 23:33:17 - 2015-04-23 23:23:49 = выходной его дает 10 минут и 32.005 секунд, но на самом деле это 0:09:28 – SS113
Вместо разделения строк используйте [Дата] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects/Date), чтобы получить нужные вам детали. То, что может быть проще, это использовать '.getTime()' для получения миллисекундных тиков и сделать простое различие на двух целых числах, а затем определить единицы времени всего за миллисекунды. – Jasen
Jasen, я могу сделать это для текущей даты/времени, но дата/время, которое я хочу вычесть из него, отформатирована как метка времени RFC 3339, и я не могу ее изменить. Может быть, я смогу преобразовать свое текущее время в метку времени RFC 3339, а затем вычесть их? – SS113