1

The UTC thing is really making me crazy... I am trying to have date and time on site in UTC so it has no affect of any timezone.

What I do, I create a date object

var d = new Date();

//convert it to utc
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); 

var utc_date = new Date(utc);
utc_date.setHours(20,0,0)

console.log(utc_date.getTime()) // I want this to be same irrespective of timezone, but don't know why it is changing

Please guide where I am doing wrong..?

UPDATED: I wanted to create a dropdown of time like on http://jsfiddle.net/HNyj5/ the concept here is I use a timestamp either from client side of selected date or from db and then I generate this dropdown dynamically. So I want the timestamp to be similar on both server/client thats why I am trying to use UTC date object.

makki
  • 2,097
  • 3
  • 23
  • 34

3 Answers3

1

You can retrieve the UTC datetime from local time like this (example timezone = GMT+0100):

var currentUTC = new Date; //=>Mon Mar 18 2013 13:53:24
currentUTC.setMinutes(currentUTC.getMinutes()+currentUTC.getTimezoneOffset();
 //=> currentUTC now: Mon Mar 18 2013 12:54:06

//or
var someUTC = new Date('1998/03/18 13:52'); //=> Wed Mar 18 1998 13:52:00
someUTC.setMinutes(currentUTC.getMinutes()+currentUTC.getTimezoneOffset();
 //=> someUTC now: Wed Mar 18 1998 12:52:00

Or as a Date Extension with a one liner:

Date.prototype.UTCFromLocal = function(){
  var a;
  return new Date(Date.prototype.setMinutes
          .call(a = this,a.getMinutes()+a.getTimezoneOffset()));
}
// usage (current date and time = Mon Mar 18 2013 14:08:14 GMT+0100
var d = new Date().UTCFromLocal(); //=> Mon Mar 18 2013 13:08:14

And to retrieve (from a UTC datetime) you could use:

Date.prototype.LocalFromUTC = function(){
  var a;
  return new Date(Date.prototype.setMinutes
          .call(a = this,a.getMinutes()-a.getTimezoneOffset()));
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Are you using the local-timezone output `toString()` to output the UTC string of `currentUTC`? `new Date()` *is* UTC already, you just have to use `toUTCString()` to see it – Bergi Mar 18 '13 at 13:02
  • No, I'm just using `toString` here – KooiInc Mar 18 '13 at 13:04
  • The problem with your `UTCFromLocal` function is that your result `Mon Mar 18 2013 13:08:14` is still in `GMT+0100` – Bergi Mar 18 '13 at 13:13
  • AFAIK the OP looks for a UTC date-time, not a date string. The converted Date using the `UTCFromLocal` method could be stored as a timestamp using `new Date().UTCFromLocal().getTime()` and retrieved as local using `[new Date(someconverteddatetime)].LocalFromUTC()` – KooiInc Mar 18 '13 at 13:18
  • But date-times in JS are timezone-less and "UTC" by default. So just `new Date().getTime()` for storing and `new Date(timestamp)` for retrieving, then getting `toString()` for local or `toUTCString()` for UTC string reference. – Bergi Mar 18 '13 at 15:43
0

Please guide where I am doing wrong..?

You are building a utc_date that is a completely different time, somehow biased by the getTimezoneOffset. Just do

var d = new Date();
d.getTime(); // milliseconds since epoch

or

Date.now();

And if you're working in UTC-land, you should use d.setUTCHours instead of the local-timezone-dependent setHours.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks Bergi, utc_date is not completely different, you see I am generating a new date (utc_date) on the basis of timestamp which is using current date as reference – makki Mar 18 '13 at 13:07
  • But why do you create a different timestamp (`utc`) in the first place? – Bergi Mar 18 '13 at 13:10
  • I am using it for making a UTC date object. So that I can work on that object, you can see what I am trying to get on jsfiddle http://jsfiddle.net/HNyj5/ – makki Mar 18 '13 at 13:16
  • There are no "UTC" date objects - `Date` objects in JS have no timezone information. You can get the UTC representation via `toUTCString()` or `toString` for local representation (which is unfortunately the default) – Bergi Mar 18 '13 at 15:44
  • On the fiddle: I'm not sure what it is supposed to do. Only I can tell you that multiplying the timestamps with 1000 results in weird values, have a look at their actual values at http://jsfiddle.net/HNyj5/1/ (where I'm storing the ISO string representation in the option values) – Bergi Mar 18 '13 at 16:05
0

Actually what I was expecting the JS to do was if I pass the timestamp in the Date constructor it should make object w.r.t that timestamp but it converts it to localtimezone which was making issues for me.

So what I did for solving this problem I get the date object by passing the string of the selected date.

var date = new Date(selected_date_str); rather than passing the timestamp

as I was making dropdown of time with UTC timestamp as its value. The start hour:min of dropdown was dynamic, which I was passing as argument in the function, it was from_hr like if I want to create dropdown of time from 20:00 then I pass from_hr = 20

so now I set hour for the selected date

date.setHours(from_hr, 0, 0);

then I made a utc_time variable for making the the value for dropdown

var utc_time = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), from_hr, 0, 0, 0);

this will retain in all timezones, this is what I am going to use as the base. Then in the loop I was adding 15 mins in the time

    var count = 0;
    jQuery(elem).html('');
    while(count <= 95){
        var option = '<option value="{0}">{1}:{2}</option>'.format(utc_time/1000, ('0' + date.getHours()).slice(-2), ('0' + date.getMinutes()).slice(-2)); //here i used a format prototype, which you can find in the jsfiddle link of my question
        jQuery(elem).append(option);
        utc_time += 15 * 60 * 1000; //adding 15 mins in the utc timestamp
        date.setMinutes(date.getMinutes() + 15)
        count++; }

I was dividing the utc_time with 1000 to make it php compatible, because I was going to retrieve value from here and save in db.

makki
  • 2,097
  • 3
  • 23
  • 34