0

Possible Duplicate:
JSON Scraping - Convert military time to standard time via Javascript

My input is e.g.

0400

0915

1200

1615

0015

I need to convert them to e.g

04:00am

09:15am

12:00pm

04:15pm

00:15am

Is there any scripts available that I can make use of?

Community
  • 1
  • 1
Emerson F
  • 805
  • 3
  • 9
  • 17

4 Answers4

2
var getFormattedTime = function (fourDigitTime){
    var hours24 = parseInt(fourDigitTime.substring(0,2));
    var hours = ((hours24 + 11) % 12) + 1;
    var amPm = hours24 > 11 ? 'pm' : 'am';
    var minutes = fourDigitTime.substring(2);

    return hours + ':' + minutes + amPm;
};

Here's a fiddle to test it.

Briguy37
  • 8,342
  • 3
  • 33
  • 53
  • I cracked my brain to think of a solution to try replacing time direct from HTML using the replace solution I found from other thread. $("body").html($("body").html().replace(/1800/g,6:00pm)); – Emerson F Jan 19 '13 at 08:17
  • Should I start a new thread for this question? – Emerson F Jan 19 '13 at 08:18
1

Use Date? I'm pretty sure it can do this.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

Halcyon
  • 57,230
  • 10
  • 89
  • 128
0

They are plenty of librairies to handle dates and times, you can use dateJS for that purpose.

Benoit Wickramarachi
  • 6,096
  • 5
  • 36
  • 46
0

The below script give the output you except...

Try it....

<script type="text/javascript">
var dtval = "0915"; //Time in 24hrs

 alert(fomartTimeShow(dtval[0] + dtval[1],dtval[2] + dtval[3]));

 function fomartTimeShow(h_24,h_min) {
     var h = h_24 % 12;
     if (h === 0) h = 12;
     return (h < 10 ? "0" + h : h) + ":" + h_min + (h_24 < 12 ? 'am' : 'pm');
}
</script>
Pandian
  • 8,848
  • 2
  • 23
  • 33