Time Conversion
HackerRank 問題: Time Conversion
		
		Categories:
Question
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.
 

Answer
<?php
/*
 * Complete the 'timeConversion' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts STRING s as parameter.
 */
function timeConversion($time_string) {
    // get time format
    $time_format = substr($time_string, -2);
    // get time for 12h format
    $time_12h = substr($time_string, 0, -2);
    // get all hour, minute, second
    [$hour, $minute, $second] = explode(':', $time_12h);
    if ($time_format == 'AM') {
        // if is AM
        if ($hour == '12') {
            // if hour is 12 than change to 0
            $hour = '0';
        }
    }
    if ($time_format == 'PM') {
        // if is PM
        if ($hour < 12) {
            // if hour is less 12, add 12 hour
            $hour = $hour + 12;
        }
    }
    $time_24h = sprintf("%02d:%02d:%02d", $hour, $minute, $second);
    return $time_24h;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$s = rtrim(fgets(STDIN), "\r\n");
$result = timeConversion($s);
fwrite($fptr, $result . "\n");
fclose($fptr);