Alko Alko - 1 year ago 199
Javascript Question

Javascript Invalid Date to string format

I'm trying to parse time which is retrieved from MySql via jSon

something like:

new Date('12:15:24').toString('h:mmtt');

but I keep getting Invalid Date in console

What I need to do is convert 24 hour format into 12 hour am/pm and vice versa

Answer Source

The Date() constructor only likes a very restricted set of date formats. If your input format is fixed at 'hh:mm:ss' it is probably easier to format it using a simple string replace:

function formatTime(time) {
  return time.replace(/(\d?\d)(:\d\d):(\d\d)/, function(_, h, m) {
    return (h > 12 ? h-12 : +h === 0 ? "12" : +h) + m + (h >= 12 ? "pm" : "am");

console.log( formatTime('00:15:24') );
console.log( formatTime('09:15:24') );
console.log( formatTime('10:15:24') );
console.log( formatTime('11:15:24') );
console.log( formatTime('12:15:24') );
console.log( formatTime('13:15:24') );
console.log( formatTime('14:15:24') );

Further reading:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download