javascript - 在 Javascript 中移动(而不是卡住)日期/时间

标签 javascript date datetime

我正在寻找一种方法将浏览器的日期更改为指定日期而不卡住时间。假设我有一些函数 shiftDate() 可以做到这一点。以下概述了我正在寻求的行为:

// Here's the current time.
new Date().getTime(); //=> 1391109350382
//
// Now let's call the function to shift/travel back in time and _immediately_
// check the time afterwards
shiftDate('2014-01-01');
new Date().getTime(); //=> 1388534400000
// 
// Now let's wait 1111 ms and then check the time again
new Date().getTime(); //=> 1388534401111
//
// Let's wait another 1111 ms
new Date().getTime(); //=> 1388534402222
//
// Let's shift/travel back in time once more
shiftDate('2014-01-01');
new Date().getTime(); //=> 1388534400000
//
// Then wait 1111 ms again
new Date().getTime(); //=> 1388534401111
//
// And wait 1111 ms again
new Date().getTime(); //=> 1388534402222

每次轮类后,通知时间都会滴答作响。我发现的大多数解决方案都通过某种模拟或 stub 完全卡住时间。然而,卡住时间并不是一个合适的解决方案:这样做会破坏其他与时间相关的功能,例如动画。下面是一个卡住时间的示例:

new Date().getTime(); //=> 1391109350382
var oldDate = Date;
Date = function() { return new oldDate('2014-01-01'); };
var testDate = new Date();
new Date().getTime(); //=> 1388534400000
// Wait 1111 ms, ten minutes, or an hour: time will never change
new Date().getTime(); //=> 1388534400000

最佳答案

查看 Momentjs 以方便地进行日期和时间操作。

http://momentjs.com/

关于javascript - 在 Javascript 中移动(而不是卡住)日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21463476/

相关文章:

javascript - wow.js 的问题

json - 使用postman发送请求后,spring boot服务器返回错误400

python - 如何在 Django 中测试 auto_now_add

c++ - 在 C++ 中格式化日期

python - 在 DataFrame 中将 Pandas 系列转换为 DateTime

php - 通过 iframe 上传文件在 IE 中不起作用

javascript - 使用 QWebElements 填写网页表单

javascript - 当向查询选择器传递变量时,CasperJS 找不到链接

mysql - 转换 - 9 十一月 2000 至 9/11/2000

postgresql - 为什么这个 crosstab() 查询返回重复键?