Time Conversion

  • + 0 comments
    #!/usr/bin/swift
    
    /*
     06-time-conversion.swift 
     https://www.hackerrank.com/challenges/time-conversion
    
     Created by Fernando Fernandes on 2/27/16.
     Copyright © 2016 Bigorna. All rights reserved.
     http://stackoverflow.com/users/584548/ferunandu
    
     !!! INSTRUCTIONS !!!
     - chmod a+x 06-time-conversion.swift
     - ./06-time-conversion.swift
    */
    
    import Foundation
    
    var amPmTime = ""
    var militaryTime: [String] = [String]()
    
    func convertToMilitaryTime() {
    
        // Remove ":"
        militaryTime = amPmTime.characters.split(":").map(String.init)
    
        // Logic for "PM"
        if (militaryTime[2].containsString("P")) {
            if (Int(militaryTime[0]) != 12) {
                militaryTime[0] = String(Int(militaryTime[0])! + 12)
            }
    
        // Logic for "AM"
        } else {
            if (Int(militaryTime[0]) == 12) {
                militaryTime[0] = "00"
            }
        }
    
        // Remove "AM" or "PM"
        militaryTime[2] = militaryTime[2].substringToIndex(militaryTime[2].startIndex.advancedBy(2))
    }
    
    print("Type the time in AM/PM format (e.g.: 07:05:45PM), then press ENTER")
    amPmTime = readLine()!
    convertToMilitaryTime()
    print(militaryTime.joinWithSeparator(":"))