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

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?

CCNA 1 Final Exam 2011 latest (hot hot hot)

  Hi! I have been posted content of ccna1 final exam (latest and only question.) I will post the answer and insert image on sunday. If you care, please subscribe your email an become a first person have full test content. Subcribe now  Some question  have not content because this question have images content. So that can you wait for me? SUNDAY 1. A user sees the command prompt: Router(config-if)# . What task can be performed at this mode? Reload the device. Perform basic tests. Configure individual interfaces. Configure individual terminal lines. 2. Refer to the exhibit. Host A attempts to establish a TCP/IP session with host C. During this attempt, a frame was captured with the source MAC address 0050.7320.D632 and the destination MAC address 0030.8517.44C4. The packet inside the captured frame has an IP source address 192.168.7.5, and the destination IP address is 192.168.219.24. At which point in the network was this packet captured? leaving host A leaving ATL leaving...