Completed
Push — master ( dc6729...95fbe4 )
by Christian
04:22
created

DateTime   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 54
rs 10
c 2
b 0
f 0
wmc 11
lcom 0
cbo 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getDifferenceAsString() 0 4 1
D difference() 0 30 10
1
<?php
2
3
namespace N98\Util;
4
5
use DateTime as PhpDateTime;
6
7
class DateTime
8
{
9
    /**
10
     * Human-readable string with time difference
11
     *
12
     * @param PhpDateTime $time1
13
     * @param PhpDateTime $time2
14
     *
15
     * @return string
16
     */
17
    public static function difference(PhpDateTime $time1, PhpDateTime $time2)
18
    {
19
        if ($time1 == $time2) {
20
            return '0';
21
        }
22
23
        $interval = $time1->diff($time2);
24
        $years = $interval->format('%y');
25
        $months = $interval->format('%m');
26
        $days = $interval->format('%d');
27
        $hours = $interval->format('%h');
28
        $minutes = $interval->format('%i');
29
        $seconds = $interval->format('%s');
30
31
        $differenceString = trim(
32
            ($years ? $years . 'Y ' : '')
33
            . ($months ? $months . 'M ' : '')
34
            . ($days ? $days . 'd ' : '')
35
            . ($hours ? $hours . 'h ' : '')
36
            . ($minutes ? $minutes . 'm ' : '')
37
            . ($seconds ? $seconds . 's ' : '')
38
        );
39
40
        if (!strlen($differenceString)) {
41
            $milliseconds = max(0, $time2->format("u") / 1000 - $time1->format("u") / 1000);
42
            $differenceString = $milliseconds ? sprintf('%0.2fms', $milliseconds) : '';
43
        }
44
45
        return $differenceString;
46
    }
47
48
    /**
49
     * Returns a readable string with time difference
50
     *
51
     * @param PhpDateTime $time1
52
     * @param PhpDateTime $time2
53
     *
54
     * @return string
55
     */
56
    public function getDifferenceAsString(PhpDateTime $time1, PhpDateTime $time2)
57
    {
58
        return self::difference($time1, $time2);
59
    }
60
}
61