Monday, July 14, 2014

Unversial Time Coordinated what the heck is the javascript offset giving me?

I generally don't have to give a lot of thought to tracking time. Give anything a timestamp and when you need it hopefully it will be enough info to solve the issue...however sometimes you have a requirement that requires you to think a little more about it...
So if you are like me, you are starting at zippo. You have heard of UTC and kind of know what it is but not really how it is used. So UTC is the baseline, the middle. I guess in Greenwhich or wherever. I honestly don't know. So if you move left or right of that time you either add or subtract in progressive increments. So you may be in a timezone marked as GMT -5 or GMT +2. Great.
So when store a UTC datetime value to the database you are grabbing the "base time" at that moment. And later when you want to see that time in Central Standard Time or Eastern Standard Time you have to add that increment to that time. (Daylight savings time is another layer of crazy that has to be figured in too).
So say you are in javascript and you have this date/time that has the date, UTC time and GMT value. Lucky you! And now you want to display that time in the user's local time. You come across this javascript function:
var offset = new Date(yourGreatDate).getTimezoneOffset();
Good. You think this function is going to tell me the offset and then I will take that value and add it to the time.
Not quite right. I *think* it depends if you are going from UTC to a certain GMT or if you going from a GMT to a UTC....
If you are converting from UTC to GMT you will need to multiply that given value by -1. The function is giving you the 'opposite' of what you want...
So if you are normally Central Standard Time which is normally GMT -6, it gives you 360. If it is Daylight Saving Time it uses GMT -5 which gives you a 300. Notice it is giving a positive number in these cases. If you are GMT +2 it gives you -120! So complicated...
So in the CST case, UTC is actually ahead of the time you want, you will need to subtract that 360 it gives you. Well first divide it by 60 then subtract it. If you have a UTC time of say 19:22 it should display it to the user as 13:22 or 01:22.
If you add minutes without multiplying by -1 you will get non-sensical information because you will be adding more time to the UTC rather than kindly bringing it back to CST...
Now, I think if you are going from a users local time and want to convert that to UTC then you use the value given.
I know this probably isn't the most useful blogpost and I am really just writing this for me to later reference when I need to refresh my memory on UTC again...

No comments:

Post a Comment