UTC to Local

One of the problems with doing date processing in JavaScript is that you are reliant on your visitors having their computer clock correctly configured so that it provides the browser with the correct local time. They also need the timezone set correctly so that their computer can switch to and from daylight saving time on the correct days if they live somewhere that uses daylight saving.

If we assume that all our visitors do have their clock correctly set (and there's nothing we can do about it if they don't) then the normal date and time methods will work correctly for their local time while the UTC equivalents to those methods will work correctly with the UTC timezone.

The problem with using local time is that it will be dependent on your visitor's timezone. Unless they are in the same timezone as you their time will be different from yours. The problem with using UTC time is that unless your visitors are in that timezone and don't use daylight saving then that time is going to be different to what they are expecting as it isn't their local time.

So what do we do when we want the time processing to work the same for everyone regardless of their timezone while still having the times display in the way they expect? Well there's nothing stopping you from entering the date/times using UTC and converting to each visitor's local time. By doing this you can set times that will apply the same to everyone (just as long as they have their timezone and local lime set correctly on their computer clock). Of course you need to calculate the UTC equivalent of your local time but you only need to do that once. Of course then we need a way to enter that into our script in a way that will prevent it being affected by whatever local time the computer is set to.

The UTCtoLocal function below allows your UTC value to be stored in an ordinary date field. Even though the time will be treated as being local time if we just access it directly, the function uses the supposed local time to set up the UTC time in a separate date field. That separate date field will then present the local time corresponding to the UTC time in the original date field which is what we want for our processing.

var UTCtoLocal = function(dtutc) {
return new Date(Date.UTC(dtutc.getFullYear(), dtutc.getMonth(), dtutc.getDate(), dtutc.getHours(), dtutc.getMinutes(), dtutc.getSeconds()));
}

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate