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

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex