javascriptdateutc

javascript - UTC date object manipulation


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.


Solution

  • 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.