Search code examples
javascriptdatetimeutc

Determine current local and UTC time when user visits webpage (JavaScript)


I wrote a basic function which was intended to grab a timestamp, for logging purposes, for when each visitor hits the page. I actually want to record the time in two ways; the local time (so I can see the distribution of visits based on the users' times) as well as the UTC time (so I can see the distribution of visits from a global, normalised perspective)

var currentTime = new Date();
var timestamp = splitTimestamp(currentTime);

function splitTimestamp(timestamp) {
    var splitTimestamp = {};
    splitTimestamp.local = new Date(timestamp.getFullYear(), timestamp.getMonth(), timestamp.getDate(), timestamp.getHours(), timestamp.getMinutes(), timestamp.getSeconds()).toISOString();
    splitTimestamp.UTC = new Date(timestamp.getUTCFullYear(), timestamp.getUTCMonth(), timestamp.getUTCDate(), timestamp.getUTCHours(), timestamp.getUTCMinutes(), timestamp.getUTCSeconds()).toISOString();
    return splitTimestamp;
}

The idea being that I can just refer to each via timestamp.local or timestamp.UTC as necessary.

I had assumed that the local time derived via new Date() would just be the local time as per the browser, i.e. as per the user's local system / OS. However, I have seen a number of records which seem to contradict that. For example, I found a record from a user in New York (UTC+4) where the time had not occurred yet (i.e. it was 11am EST / 3pm UTC when I saw the record but it was showing as 2pm EST / 6pm UTC in the log)

Now - initially, I accounted for this by saying the user may simply be using system settings that don't necessarily align with their physical location (i.e. they were in New York but, for reasons known only to themselves, they keep their system / OS on UTC time) And there's nothing I can do about that, I am comfortable with that.

But... If that were the case, then the local time and the UTC time would be the same? And... they're not. So... that can't be what's happening?

Is there something obvious I'm overlooking here?


Solution

  • If you just want a time string that is in that format, you can duplicate the date object using new Date(date) (no reason to put the year, month, date, etc), and then subtract the offset and get the ISO formatted string. You should then remove the 'z' at the end of the string to indicate that it's the local timezone rather than a UTC timezone.

    var date = new Date();
    var utc_time = date.toISOString();
    
    var offset_date = new Date(date);
    offset_date.setMinutes(date.getMinutes()-date.getTimezoneOffset());
    var local_time = offset_date.toISOString().slice(0, -1);
    
    console.log(utc_time);
    console.log(local_time);

    You may also be interested in looking at my ProtoDate library. I built it to handle stuff like this.