我试着在几秒钟内分辨出两个日期的区别。逻辑是这样的:

设定一个初始日期,可以是现在; 设置最终日期,即初始日期加上未来的某一秒数(例如15秒) 得到两者的差值(秒数)

为什么我这样做的原因,它与日期,这是因为最终日期/时间取决于一些其他变量,它是不一样的(这取决于用户做某事的速度),我也为其他事情存储初始日期。

我一直在尝试这样的事情:

var _initial = new Date(),
    _initial = _initial.setDate(_initial.getDate()),
    _final = new Date(_initial);
    _final = _final.setDate(_final.getDate() + 15 / 1000 * 60);

var dif = Math.round((_final - _initial) / (1000 * 60));

问题是我从来没有找到正确的区别。我试着用24 * 60除以秒,但我从来没有做对。我的逻辑有什么问题吗?我可能犯了一些愚蠢的错误,因为已经很晚了,但它困扰着我,我不能让它工作:)


当前回答

  const getTimeBetweenDates = (startDate, endDate) => {
  const seconds = Math.floor((endDate - startDate) / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  return { seconds, minutes, hours, days };
};

其他回答

<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();

var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>

你可以使用new Date(). gettime()来获取时间戳。然后你可以计算结束和开始之间的差异,并最终将时间戳ms转换为s。

const start = new Date().getTime();
const end = new Date().getTime();

const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);

下面的代码将给出以秒为单位的时间差。

进口的基础

var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
    
alert(timeDiffInSecond );
  const getTimeBetweenDates = (startDate, endDate) => {
  const seconds = Math.floor((endDate - startDate) / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  return { seconds, minutes, hours, days };
};

现在和10分钟后使用momentjs的时差

let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');

let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;