Skip to main content

How do you convert a JavaScript date to UTC?


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 the server expects all dates and times to be in UTC.



Now suppose the user is in Alaska or Hawaii or Fiji. Since they are in a timezone quite different from UTC, the date range needs to be converted to something like this:




2009-1-1T8:00:00 to 2009-1-4T7:59:59



Using the JavaScript Date object, how would you convert the first "localized" date range into something the server will understand?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. Simple and stupid

    var now = new Date();
    var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());

    ReplyDelete
  2. 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(':');
    }

    ReplyDelete
  3. 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');

    ReplyDelete
  4. 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.

    ReplyDelete
  5. I prefer this approach:

    var now = new Date();

    var utc = new Date(Date.UTC(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    now.getHours(),
    now.getMinutes()
    ));

    // now = Thu Mar 01 2012 06:28:00 GMT-0800 (PST)
    // utc = Wed Feb 29 2012 22:28:00 GMT-0800 (PST)


    Date.UTC() returns the number of milliseconds since the epoch, UTC.

    Docs here

    Cheers

    ReplyDelete
  6. I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.

    You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:

    $.parseDate('yy-mm-dd', '2007-01-26');

    ReplyDelete
  7. var myDate = new Date(); // Set this to your date in whichever timezone.
    var utcDate = myDate.toUTCString();

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...