javascript - 计算两个时间戳之间的差异并获得 unix 时间戳的差异

标签 javascript jquery datetime datepicker

我想计算两个日期时间之间的差异,一个日期是用户提交的,另一个是当前时间:

user submitted time - now = difference in unix

用户提交的时间格式为:

2014-03-26 10:52:00

感谢您的帮助。

最佳答案

您可以简单地使用 getTime() 来做到这一点返回毫秒数。

var ds = "2014-03-26 10:52:00"; 
var newDate = new Date(ds).getTime(); //convert string date to Date object
var currentDate = new Date().getTime();
var diff = currentDate-newDate;
console.log(diff);

有时在解析日期字符串时有可能实现跨浏览器兼容性所以最好像这样解析它

var ds = "2014-03-26 10:52:00";
var dateArray = ds.split(" ");  // split the date and time 
var ds1 = dateArray[0].split("-"); // split each parts in date
var ds2 = dateArray[1].split(":"); // split each parts in time
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
var currentDate = new Date().getTime();
var diff = currentDate - newDate;
console.log(diff); //timestamp difference

关于javascript - 计算两个时间戳之间的差异并获得 unix 时间戳的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22652136/

相关文章:

javascript - 当页面刷新时,AngularJS 到底会发生什么?

jquery - 如何获取重复控件中的元素id

javascript - PHP 与 Javascript 的迭代比较

ruby-on-rails - Rails 的 future 日期

c# - 从 EST/EDT 转换为 GMT

javascript - 无法通过更改宽度或 Flex-basis 来隐藏 Flex 元素

javascript - Heroku 没有运行 gulp 吗?

php - 如何将 PHP、Javascript 和 HTML 文档合并为一个?

javascript - 易于切换的背景

python - 在 Python 中为启用了真除法的日期时间模块计算 total_seconds