如何在javascript中将当前时间设置为其他时间

Cra*_*ooB 5 javascript time

我试图将当前时间设置为其他时间,每当我尝试访问当前时间时,我需要获得新的时间.假设我当地的机器当前时间是凌晨2点.但我希望将其更改为上午10点,当我访问时,当前时间应该从上午10点开始,而不是凌晨2点.

例如:

var x = new Date();
Run Code Online (Sandbox Code Playgroud)

如果你看到x.getHours()提取我的当地时间是凌晨2点,并且每次它都以凌晨2点作为基础.

但我需要将其更改为上午10点,以便我的新Date()给出上午10点,并根据该值每秒钟保持滴答作响.

我不想为此目的使用setInterval().我确定有setInterval()的解决方案.但问题是我有多个setIntervals,另一个是停止更新setInterval()中的时间,我试图每秒上午10点更新.

Ren*_*nan 6

您无法从Javascript更改系统时间,而不是从浏览器运行.您需要一个特殊的环境,一个能够连接javascript和操作系统的API来实现这一点的环境.这不是一件简单的事情,可能超出了您正在处理的应用程序的范围.

我建议您创建一个函数/对象,其中包含使用偏移量获取当前日期的方法.像这样:

Foo = function () {};
Foo.prototype.offset = 8;
Foo.prototype.getDate = function () {
    var date = new Date();
    date.setHours(date.getHours() + this.offset);
    return date;
}
Run Code Online (Sandbox Code Playgroud)

现在您可以实例化a foo,设置偏移量(默认为8)并使用它.当您需要抵消小时时,您可以:

var foo = new Foo();
var bar = foo.getDate();
Run Code Online (Sandbox Code Playgroud)

bar不打勾,但每当你需要的当前日期的偏移量,你可能只是使用FoogetDate一次.

编辑:为了从固定日期开始,您可以使用如下构造函数:

Foo = function (baseDate) {
    this._date = baseDate;
    this._fetched = new Date();
}

Foo.prototype.getDate = function () {
    var now = new Date();
    var offset = now.getTime() - this._fetched.getTime();
    this._date.setTime(this._date.getTime() + offset);
    this._fetched = now;
    return this._date;
}
Run Code Online (Sandbox Code Playgroud)

请注意,now.getDay()它将返回星期几,而不是月份的那一天.因此在now.getDate()那里.(编辑使用基准日期而不是固定的,硬编码的日期).


Hub*_*iak 6

Using TimeShift.js this can be done fairly easy. in the beginning of your page include TimeShift.js and set the date explicitly. Shameless copy of its manual:

new Date().toString();                      // Original Date object
"Fri Aug 09 2013 23:37:42 GMT+0300 (EEST)"

Date = TimeShift.Date;                      // Overwrite Date object
new Date().toString();
"Fri Aug 09 2013 23:37:43 GMT+0300"

TimeShift.setTimezoneOffset(-60);           // Set timezone to GMT+0100 (note the sign)
new Date().toString();
"Fri Aug 09 2013 21:37:44 GMT+0100"

TimeShift.setTime(1328230923000);           // Set the time to 2012-02-03 01:02:03 GMT
new Date().toString();
"Fri Feb 03 2012 02:02:03 GMT+0100"

TimeShift.setTimezoneOffset(0);             // Set timezone to GMT
new Date().toString();
"Fri Feb 03 2012 01:02:03 GMT"

TimeShift.getTime();                        // Get overridden values
1328230923000
TimeShift.getTimezoneOffset();
0

TimeShift.setTime(undefined);               // Reset to current time
new Date().toString();
"Fri Aug 09 2013 20:37:45 GMT"

new Date().desc();                          // Helper method
"utc=Fri, 09 Aug 2013 20:37:46 GMT   local=Fri, 09 Aug 2013 20:37:46 GMT   offset=0"

new TimeShift.OriginalDate().toString();    // Use original Date object
"Fri Aug 09 2013 23:37:47 GMT+0300 (EEST)"
Run Code Online (Sandbox Code Playgroud)

I think this is slightly better than writing a custom Date object/function (Foo) since this library doesn't require you to rewrite existing code.