1

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;
Valerie
  • 35
  • 1
  • 7
  • 1
    take a look here http://momentjs.com – Eugene Hauptmann Feb 10 '16 at 18:59
  • Note that 2/10/2016 is an ambiguous format that in most places will be interpreted as 2 October. Better to use a format that includes the month name to remove that ambiguity. Also, reformatting the string is likely faster and simpler than converting to a Date the formatting the output. – RobG Feb 10 '16 at 23:45

2 Answers2

1

You could turn the string into a valid javascript date and then use the date methods to display it how you want to. For example to turn it into a javascript date, split it into its parts and then assemble.

var dateAndtime = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
var date = dateAndtime.split(' ')[0];
var time = dateAndtime.split(' ')[1];
var year = date.split('-')[0];
var month = date.split('-')[1]-1;
var day = date.split('-')[2];
var hour = time.split(':')[0];
var minute = time.split(':')[1];
var second = time.split(':')[2];
var d = new Date(year, month, day, hour, minute, second);
Leo Farmer
  • 7,730
  • 5
  • 31
  • 47
  • Great idea to parse the string manually, however far less code is required. Consider the answers to [*JavaScript Date.parse return NaN in Mozilla Browser*](http://stackoverflow.com/questions/35169209/javascript-date-parse-return-nan-in-mozilla-browser/35169689#35169689). – RobG Feb 10 '16 at 23:43
0

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>'))
RobG
  • 142,382
  • 31
  • 172
  • 209