SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Converting UTC time to local time

    How can I convert "2008-09-22T09:36:05+00:00" (string) to localtime in JS?

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The timestamp of any date object is in universal (GMT) time.
    For example, if your s="2008-09-22T09:36:05" is the time in Greenwich,
    it resolves to 1222076165000 milliseconds.
    That should be what you pass to the client.
    The client will adjust it to the local time:

    Code:
    var s='1222076165000';
    var d=new Date(s*1);
    alert(d);
    It is much more involved to convert a date string formatted as UTC to a local date value, even if you can trust the data.



    Code:
    var s="2008-09-22T09:36:05"; // GMT time
    
    var A=s.split(/\D+/);
    for(var i=0;i<7;i++){
    	if(!A[i])A[i]='0';
    	parseInt(A[i],10)
    }
    A[1]-=1;
    var A2=A.slice(3);
    
    var d=new Date();
    d.setUTCFullYear.apply(d,A); 
    d.setUTCHours.apply(d,A2);
    
    alert(d);

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Here try this instead.

    The parse method can take a number of formats
    http://developer.mozilla.org/en/Core...cts/Date/parse

    Code javascript:
    var s="2008-09-22T09:36:05";
    var regex = /(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})/;
    d = (Date.parse(s.replace(regex, '$2 $3, $1 $4')));
    alert(d);
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •