Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Scraping - Convert military time to standard time via Javascript

I am scraping JSON data from a url. The time is military time and I was wondering if there is a way once I retrieve on the client side to convert it to standard time.

Here is the JSON:

[
  {
    SaturdayClose: "21:00",
    SaturdayOpen: "10:00",
    SundayClose: "12:00",
    SundayOpen: "18:00",
    WeekdayClose: "21:00",
    WeekdayOpen: "10:00"
  }
]

Here is my index.html:

    <p>
        Sun: ${ SundayOpen }a - ${ SundayClose }p Mon - Sat: ${ SaturdayOpen }a ${ SaturdayClose }p
    </p>

This returns this type of ugliness:

Sun: 18:00a - 12:00p Mon - Sat: 10:00a 21:00p

I would rather return this:

Sun: 6:00a - 12:p Mon - Sat: 10:00a - 9:00p

like image 457
J0NNY ZER0 Avatar asked Dec 28 '11 15:12

J0NNY ZER0


1 Answers

Using a date script will work of course. If all you need is to convert from 24 hour clock to 12 hour, you can simply subtract the time and add the period as indicated.

EDIT

I added two times as a test, 00:30, which should be 12:30 am, and 12:15, which should be 12:15 pm. See the new edit below.

var times = {
    SaturdayClose: "21:00",
    SaturdayOpen: "10:00",
    SundayClose: "12:00",
    SundayOpen: "18:00",
    WeekdayOpen: "10:00",
    WeekdayClose: "21:00",
    WeekendOpen: "12:15",
    WeekendClose: "00:30"
};

console.log(times);

for (var time in times) {
    var parts = times[time].split(':'),
        hour = parts[0],
        minutes = parts[1];

    if (hour > 12) {
        times[time] = (hour - 12) + ':' + minutes + ' pm';
    } else if (hour == 0) {
        times[time] = 12 + ':' + minutes + ' am';
    } else if (hour == 12) {
        times[time] += ' pm';
    } else {
        times[time] += ' am';
    }
}

console.log(times);

http://jsfiddle.net/tqXCL/3/

Which gives you the following after conversion:

SaturdayClose "9:00 pm" 
SaturdayOpen  "10:00 am"    
SundayClose   "12:00 pm"    
SundayOpen    "6:00 pm" 
WeekdayClose  "9:00 pm" 
WeekdayOpen   "10:00 am"    
WeekendClose  "12:30 am"    
WeekendOpen   "12:15 pm"
like image 167
Jared Farrish Avatar answered Oct 05 '22 22:10

Jared Farrish