1

Id it possible to do something like:

var format = "ampm";
var time = '22:15:05';

if(format == "ampm") {
   return '10:15 pm';
} else {
   return '22:15';
}

All the examples that I found use new Date() with current date and time, but in my case i just need to pass time string from database.

Alko
  • 1,421
  • 5
  • 25
  • 51
  • There's a kajillion date formatting libraries out there. Why not [pick one](https://github.com/nomiddlename/date-format) and use it? – tadman Apr 15 '16 at 18:14
  • 2
    Possible duplicate of [Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone](http://stackoverflow.com/questions/13898423/javascript-convert-24-hour-time-of-day-string-to-12-hour-time-with-am-pm-and-no) – Rayon Apr 15 '16 at 18:14
  • @tadman I dont want to use a whole library just for that – Alko Apr 15 '16 at 18:16
  • You don't have to use "a whole library", you just need to find the snippet of code in that library that does what you want and put that into your application. Writing your own conversion routine is going to be messy. – tadman Apr 15 '16 at 18:16
  • @Rayon Dabre that example show how to convert from 24 hours to 12 hours am/pm but in my case i need both based on setting – Alko Apr 15 '16 at 18:17
  • Heard of `if.....else` ? – Rayon Apr 15 '16 at 18:17
  • Are the time values you want to convert always a string as shown in your code? Do the strings have a fixed format or can they arrive in any format? Without more information we can only guess at a solution. – Yogi Apr 15 '16 at 18:26
  • the values are coming from MySql, via Json so the format will always be the same 00:00:00 – Alko Apr 15 '16 at 18:40
  • Any way to convert standard time to military time? – RedBottleSanitizer Apr 27 '21 at 16:11

2 Answers2

0

Here is a function that you could use:

function timeFormat(time, format) {
    var parts = time.split(':');
    var hour = parseInt(parts[0]);
    var suffix = '';
    if (format === 'ampm') {
       suffix = hour >= 12 ? ' pm' : ' am';
       hour = (hour + 11) % 12 + 1;
    }
    return ('0' + hour).substr(-2) + ':' + parts[1] + suffix;
}

// Demo with some sample input
var input = ['00:21:13', '11:59:20', '12:01:33', '16:00:00', '23:59:59'];
for (var time of input) {
    document.write(time + ' = ' + timeFormat(time, 'ampm') + '<br>');
}

Note that it strips the seconds; there is no rounding.

trincot
  • 317,000
  • 35
  • 244
  • 286
0

Here's my way using if statements.

Note: it doesn't take seconds.

const converTime = (time) => {
  let hour = (time.split(':'))[0]
  let min = (time.split(':'))[1]
  let part = hour > 12 ? 'pm' : 'am';
  
  min = (min+'').length == 1 ? `0${min}` : min;
  hour = hour > 12 ? hour - 12 : hour;
  hour = (hour+'').length == 1 ? `0${hour}` : hour;

  return (`${hour}:${min} ${part}`)
}

console.log(converTime('18:00:00'))
console.log(converTime('6:5:00'))
console.log(converTime('23:58:24'))
avc
  • 33
  • 4