How do you convert a JavaScript date to UTC?

后端 未结 29 2083
无人共我
无人共我 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 01:06

    I know this question is old, but was looking at this same issue, and one option would be to send date.valueOf() to the server instead. the valueOf() function of the javascript Date sends the number of milliseconds since midnight January 1, 1970 UTC.

    valueOf()

    0 讨论(0)
  • 2020-11-22 01:07
    Date.prototype.toUTCArray= function(){
        var D= this;
        return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
        D.getUTCMinutes(), D.getUTCSeconds()];
    }
    
    Date.prototype.toISO= function(){
        var tem, A= this.toUTCArray(), i= 0;
        A[1]+= 1;
        while(i++<7){
            tem= A[i];
            if(tem<10) A[i]= '0'+tem;
        }
        return A.splice(0, 3).join('-')+'T'+A.join(':');    
    }
    
    0 讨论(0)
  • 2020-11-22 01:08

    Here's my method:

    var now = new Date();
    var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
    

    The resulting utc object isn't really a UTC date, but a local date shifted to match the UTC time (see comments). However, in practice it does the job.

    0 讨论(0)
  • 2020-11-22 01:08

    I just discovered that the 1.2.3 version of Steven Levithan's date.format.js does just what I want. It allows you to supply a format string for a JavaScript date and will convert from local time to UTC. Here's the code I'm using now:

    // JavaScript dates don't like hyphens!    
    var rectifiedDateText = dateText.replace(/-/g, "/");
    var d = new Date(rectifiedDateText);
    
    // Using a predefined mask from date.format.js.
    var convertedDate = dateFormat(d, 'isoUtcDateTime'); 
    
    0 讨论(0)
  • 2020-11-22 01:09
    var userdate = new Date("2009-1-1T8:00:00Z");
    var timezone = userdate.getTimezoneOffset();
    var serverdate = new Date(userdate.setMinutes(userdate.getMinutes()+parseInt(timezone)));
    

    This will give you the proper UTC Date and Time.
    It's because the getTimezoneOffset() will give you the timezone difference in minutes. I recommend you that not to use toISOString() because the output will be in the string Hence in future you will not able to manipulate the date

    0 讨论(0)
  • 2020-11-22 01:09

    Using moment.js UTC method;

    const moment = require('moment');
    const utc = moment.utc(new Date(string));
    
    0 讨论(0)
提交回复
热议问题