Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set current time to some other time in javascript

I am trying to set current time to some other time and whenever i try to access current time i need to get the new time. Suppose current time is 2 am in my local machine. But I want to change it to 10 am and current time should keep ticking from 10 am instead of 2 am whenever i access it.

Ex:

var x = new Date();

if you see x.getHours() fetches my local time which is 2 am and every time it keeps ticking with 2 am as its base.

But I need to change it to 10 am so that my new Date() gives 10 am and keeps ticking every second based on that.

I do not want to use setInterval() for this purpose. I sure have solution with setInterval(). But the thing is I have multiple setIntervals and the other one is stopping from updating the time in the setInterval() where I am trying to update 10 am every second.

like image 957
CrazyNooB Avatar asked Aug 07 '13 16:08

CrazyNooB


1 Answers

You can't change the system time from Javascript, not if it's running from the browser. You'd need a special environment, one with the ability to interface javascript and the operating system's API to do that. That's no simple thing and probably way out of the scope of the application you're working on.

I suggest you create a function/object with means to fetch the current date with an offset. Like this:

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

Now you can instantiate a foo, set the offset (8 by default) and work with it. When you need your offset hour you can just do:

var foo = new Foo();
var bar = foo.getDate();

bar will not tick, but whenever you need the current date with an offset you may just use Foo's getDate again.

Edit: In order to start from a fixed date, you can use the constructor like this:

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;
}

Notice that now.getDay() would return the day of the week, not the day of the month. Hence the now.getDate() up there. (Edited to use a base date instead of a fixed, hard-coded one).

like image 139
Geeky Guy Avatar answered Oct 07 '22 18:10

Geeky Guy