Date::timeDiffFormat()   C
last analyzed

Complexity

Conditions 9
Paths 256

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 10
ccs 9
cts 9
cp 1
rs 6.5222
cc 9
nc 256
nop 3
crap 9
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: yiranzai
5
 * Date: 19-3-22
6
 * Time: 上午11:14
7
 */
8
9
namespace Yiranzai\Tools;
10
11
use Carbon\Carbon;
12
use DateTime;
13
14
class Date
15
{
16
    /**
17
     * 生成Carbon对象,不合法数据会返回默认值
18
     *
19
     * @param       $dateTime
20
     * @param mixed $default
21
     * @return Carbon
22
     */
23 3
    public static function toCarbon($dateTime = null, $default = false)
24
    {
25 3
        if ($dateTime instanceof Carbon) {
26 3
            return $dateTime;
27
        }
28 3
        $default = empty($default) ? Carbon::now() : $default;
29 3
        if (strtotime($dateTime) > 0) {
30 3
            return Carbon::parse($dateTime);
31
        }
32
33 3
        if (is_numeric($dateTime)) {
34 3
            return Carbon::createFromTimestamp($dateTime);
35
        }
36
37 3
        return $default;
38
    }
39
40
    /**
41
     * 人性化显示两个时间的差
42
     * @param DateTime $leftTime
43
     * @param DateTime $rightTime
44
     * @param bool     $absolute
45
     * @return string
46
     */
47 3
    public static function timeDiffFormat(DateTime $leftTime, DateTime $rightTime, $absolute = false): string
48
    {
49 3
        $diff = $leftTime->diff($rightTime, $absolute);
50 3
        return ($absolute && !$diff->invert ? '-' : '')
51 3
            . ($diff->y ? $diff->y . '年' : '')
52 3
            . ($diff->m ? $diff->m . '月' : '')
53 3
            . ($diff->d ? $diff->d . '日' : '')
54 3
            . ($diff->h ? $diff->h . '小时' : '')
55 3
            . ($diff->i ? $diff->i . '分钟' : '')
56 3
            . ($diff->s ? $diff->s . '秒' : '');
57
    }
58
}
59