How do you convert a JavaScript date to UTC?

后端 未结 29 2081
无人共我
无人共我 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.

    0 讨论(0)
  • 2020-11-22 00:59

    This method will give you : 2017-08-04T11:15:00.000+04:30 and you can ignore zone variable to simply get 2017-08-04T11:15:00.000.

    function getLocalIsoDateTime(dtString) {
        if(dtString == "")
            return "";
        var offset = new Date().getTimezoneOffset();
        var localISOTime = (new Date(new Date(dtString) - offset * 60000 /*offset in milliseconds*/)).toISOString().slice(0,-1);
        //Next two lines can be removed if zone isn't needed.
        var absO = Math.abs(offset);
        var zone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(absO / 60)).slice(-2) + ":" + ("00" + (absO % 60)).slice(-2);
        return localISOTime + zone;
    }
    
    0 讨论(0)
  • 2020-11-22 01:02

    Simple and stupid

    var date = new Date(); 
    var now_utc =  Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),
     date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    
     return new Date(now_utc);
    
    0 讨论(0)
  • 2020-11-22 01:04

    My recommendation when working with dates is to parse the date into individual fields from user input. You can use it as a full string, but you are playing with fire.

    JavaScript can treat two equal dates in different formats differently.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

    Never do anything like:

    new Date('date as text');
    

    Once you have your date parsed into its individual fields from user input, create a date object. Once the date object is created convert it to UTC by adding the time zone offset. I can't stress how important it is to use the offset from the date object due to DST (that's another discussion however to show why).

    var year = getFullYear('date as text');
    var month = getMonth('date as text');
    var dayOfMonth = getDate('date as text');
    
    var date = new Date(year, month, dayOfMonth);
    
    var offsetInMs = ((date.getTimezoneOffset() * 60)  // Seconds
                     * 1000);                          //  Milliseconds
    
    var utcDate = new Date(date.getTime + offsetInMs);
    

    Now you can pass the date to the server in UTC time. Again I would highly recommend against using any date strings. Either pass it to the server broken down to the lowest granularity you need e.g. year, month, day, minute or as a value like milliseconds from the unix epoch.

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

    This function works beautifully for me.

    function ParseDateForSave(dateValue) {
        // create a new date object
        var newDate = new Date(parseInt(dateValue.substr(6)));
    
        // return the UTC version of the date
        return newDate.toISOString();
    }
    
    0 讨论(0)
  • 2020-11-22 01:05

    Browsers may differ, and you should also remember to not trust any info generated by the client, that being said, the below statement works for me (Google Chrome v24 on Mac OS X 10.8.2)

    var utcDate = new Date(new Date().getTime());


    edit: "How is this different than just new Date()?" see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    • If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
    • Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments. (note: Date.UTC() returns the number of millisecond since 1970-01-01 00:00:00 UTC)

    Adding the 60000 * Date.getTimezoneOffset() as previous answers have stated is incorrect. First, you must think of all Dates/Times as already being UTC with a timezone modifier for display purposes.

    Again, browsers may differ, however, Date.getTime() returns the number of milliseconds since 1970-01-01 UTC/GMT. If you create a new Date using this number as I do above, it will be UTC/GMT. However, if you display it by calling .toString() it will appear to be in your local timezone because .toString() uses your local timezone, not the timezone of the Date object it is called on.

    I have also found that if you call .getTimezoneOffset() on a date, it will return your local timezone, not the timezone of the date object you called it on (I can't verify this to be standard however).

    In my browser, adding 60000 * Date.getTimezoneOffset() creates a DateTime that is not UTC. However when displayed within my browser (ex: .toString() ), it displays a DateTime in my local timezone that would be correct UTC time if timezone info is ignored.

    0 讨论(0)
提交回复
热议问题