how can I subtract time from time for time remaining?

会有一股神秘感。 提交于 2019-12-22 10:24:04

问题


Using JavaScript, How can I subtract from HH:MM:SS?

For example, I have 12:54:45 and I want to subtract 11:35:53 for remaining time in 4732 seconds


回答1:


var first = (new Date('Jan 01, 2000 12:54:45')).getTime();
var second = (new Date('Jan 01, 2000 11:35:53')).getTime(); 
var differenceInSeconds = (second - first) / 1000;
// 4732

I chose 2000-01-01 as the date, as it does not matter as long it is the same. We only want to calculate the difference.




回答2:


This works

(Date.parse('January 1, 1970 12:54:45') - Date.parse('January 1, 1970 11:35:53')) / 1000

Output is 4732




回答3:


There are libraries that makes possible to manipulate dates in an easy way: moment.js and day.js are two examples of choice.

// moment.js example
moment()
  .add(7, 'days')
  .subtract(1, 'months')
  .year(2009)
  .hours(0)
  .minutes(0)
  .seconds(0);

More...

// day.js example
dayjs().add(7, 'day');

More...

Also, for seconds manipulation, Unix time can be useful. It allows to describe time as the number of seconds elapsed since 1st January 1970.



来源:https://stackoverflow.com/questions/17256381/how-can-i-subtract-time-from-time-for-time-remaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!