santa
santa

Reputation: 12512

User current time

I have a script that stores an action taken by a user. There's a column that contains datetime and originally I user NOW(), but that uses server time, which is a few hours off as compared to the user's actual time.

So I decided I'll use the time that I can get with JS. I've formatted it this way:

var now   = new Date(),                
    isnow = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + ('0' + now.getDate()).slice(-2) + ' ' + ('0' + (now.getHours() + 1)).slice(-2) + ':' + ('0' + now.getMinutes()).slice(-2) + ':' + ('0' + now.getSeconds()).slice(-2);

I've tested and while the format works fine, the time is off by an hour. Is it because of the Daylight Savings Time? How do I get the actual local time for the user?

Upvotes: 0

Views: 60

Answers (2)

Gilberto Galea
Gilberto Galea

Reputation: 61

In your code wrote:

...('0' + (now.getHours() + 1)).slice(-2)...

Try to remove this plus one

Additional you can check if Day Savings Time with:

if (now.dst()) { alert ("Daylight savings time!"); }

Date.prototype.stdTimezoneOffset = function() {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function() {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

Based at answer similar issue

Upvotes: 2

Mr. Llama
Mr. Llama

Reputation: 20889

You should use the toISOString() method to convert the Date object to the ISO-8601 standard format:

now.toISOString();

The ISO-8601 date format puts the time information into a universal form which includes optional timezone information (likely the source of your issues).

Upvotes: 0

Related Questions