Search code examples
javascriptxmldatetimereformatting

convert xml date and time using javascript


I am pulling the some information from a stock feed. the time stamp for last update comes in like this:

2016-02-10 13:32:41

How do I format it to be like:

1:32:41pm
2/10/2016

Here is my variable declaration:

time = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;

Solution

  • There is no need to create a Date, you can just parse and reformat the string. You have to parse the string anyway, reformatting without a Date is just more efficient.

    // 2016-02-10 13:32:41 => m/dd/yyyy h:mm:ssap
    function reformatDateString(s) {
      var b = s.split(/\D/);
      var ap = b[3] < 12? 'am':'pm';
      var h =  b[3]%12 || 12;
      return h + ':' + b[4] + ':' + b[5] + ap +
             '\n' + +b[1] + '/' + b[2] + '/' + b[0];
    }
    
    document.write(reformatDateString('2016-02-10 13:32:41').replace('\n','<br>'))
    document.write('<br>');
    document.write(reformatDateString('2016-12-09 03:02:09').replace('\n','<br>'))