Time Conversion

  • + 0 comments

    My answer with Typescript, clearly

    function timeConversion(str: string): string {
        const pad = (n: number) => n.toString().padStart(2, '0')
    
        // 0. read 12h
        let h = Number(str.substring(0, 2))
        let m = Number(str.substring(3, 5))
        let s = Number(str.substring(6, 8))
        let p = str.substring(8, 10)
    
        // 1. convert to 24h
        if (h == 12) h = 0
        if (p == 'PM') h += 12
    
        return `${pad(h)}:${pad(m)}:${pad(s)}`
    }