How do you convert a JavaScript date to UTC?

后端 未结 29 2121
无人共我
无人共我 2020-11-22 00:50

Suppose a user of your website enters a date range.

2009-1-1 to 2009-1-3

You need to send this date to a server for some processing, but th

29条回答
  •  自闭症患者
    2020-11-22 00:59

    Are you trying to convert the date into a string like that?

    I'd make a function to do that, and, though it's slightly controversial, add it to the Date prototype. If you're not comfortable with doing that, then you can put it as a standalone function, passing the date as a parameter.

    Date.prototype.getISOString = function() {
        var zone = '', temp = -this.getTimezoneOffset() / 60 * 100;
        if (temp >= 0) zone += "+";
        zone += (Math.abs(temp) < 100 ? "00" : (Math.abs(temp) < 1000 ? "0" : "")) + temp;
    
        // "2009-6-4T14:7:32+10:00"
        return this.getFullYear()   // 2009
             + "-"
             + (this.getMonth() + 1) // 6
             + "-"
             + this.getDate()       // 4
             + "T"
             + this.getHours()      // 14
             + ":"
             + this.getMinutes()    // 7
             + ":"
             + this.getSeconds()    // 32
             + zone.substr(0, 3)    // +10
             + ":"
             + String(temp).substr(-2) // 00
        ;
    };
    

    If you needed it in UTC time, just replace all the get* functions with getUTC*, eg: getUTCFullYear, getUTCMonth, getUTCHours... and then just add "+00:00" at the end instead of the user's timezone offset.

提交回复
热议问题