human time php

Solutions on MaxInterview for human time php by the best coders in the world

showing results for - "human time php"
Zack
22 Aug 2020
1// for a human time string like: "It's around ten past twelve" 
2// usage: echo 'It\'s ' . humanTime(date('h'), date('i'));
3
4function humanTime($hour, $min) {
5    $times = [
6        0 => '%s o\'clock',
7        2 => 'a couple of mins past %s',
8        5 => 'five past %s',
9        8 => 'around ten past %s',
10        10 => 'ten past %s',
11        15 => 'quarter past %s',
12        20 => 'twenty past %s',
13        25 => 'twenty five past %s',
14        27 => 'around half past %s',
15        30 => 'half past %s',
16        33 => 'around thirty five past %s',
17        35 => 'thirty five past %s',
18        40 => 'twenty to %s',
19        43 => 'around quarter to %s',
20        45 => 'quarter to %s',
21        47 => 'about ten to %s',
22        50 => 'ten to %s',
23        53 => 'about five to %s',
24        55 => 'five to %s'
25    ];
26    
27    $hourWord = [
28        'one',
29        'two',
30        'three',
31        'four',
32        'five',
33        'six',
34        'seven',
35        'eight',
36        'nine',
37        'ten',
38        'eleven',
39        'twelve'
40    ];
41
42    $hour = (int) $hour;
43    $min = (int) $min;
44    
45    $closest = null;
46    foreach ($times as $key => $item) 
47        if ($closest === null || abs($min - $closest) > abs($key - $min)) $closest = $key;
48    
49    if ($hour === 0) $hour = 12;
50    
51    if ($min > 40) $hour = $hour === 12 ? 1 : $hour + 1;
52
53    return sprintf($times[$closest], $hourWord[(int) $hour - 1]);
54}