JSON Scraping - Convert military time to standard time via Javascript

后端 未结 5 1953
终归单人心
终归单人心 2021-01-18 19:41

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.

<
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 20:19

    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"
    

提交回复
热议问题