将两个时间戳的差(秒)转化成字符串

比如“x分钟前”、“x小时前”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/**
* 时间转换易读的文字
* @author technofiend<2281551151@qq.com>
* https://blog.csdn.net/technofiend/article/details/78627161
*/
function time2Readability($time, $contrastTime = 0)
{
if ($contrastTime <= 0) {
$contrastTime = time();
}

if ($time <= 0) {
return '未知';
}

// 非今年发布的时间
if (date('Y', $time) != date('Y', $contrastTime)) {
return date('Y-m-d H:i:s', $time);
}

// 发布时间的零点
$dateTime1 = new \DateTime();
$dateTime1->setTimestamp($time);
$dateTime1->setTime(0, 0, 0);
$time1 = $dateTime1->getTimestamp();

// 今天的零点
$todayObj = new \DateTime();
$todayObj->setTimestamp($contrastTime);
$todayObj->setTime(0, 0, 0);
$today = $todayObj->getTimestamp();

// 距离发表时间的秒数
$elapseTime = $contrastTime - $time;

// 发表时间等于今天
if ($time1 == $today) {
// 今天发表的
if ($elapseTime <= 5 * 60) {
// 5分钟内
return '刚刚';
} else if ($elapseTime <= 60 * 60) {
// 一个钟头内
return floor($elapseTime / 60) . ' 分钟前';
} else {
return floor($elapseTime / (60 * 60)) . ' 小时前';
}
}

$dateTime3 = new \DateTime();
$dateTime3->setTimestamp($contrastTime);
$dateTime3->modify('-1 day');
$dateTime3->setTime(0, 0, 0);
$yesterday = $dateTime3->getTimestamp();

// 发表时间等于昨天
if ($time1 == $yesterday) {
if (($contrastTime - 6 * 60 * 60) < $today) {
// 如果当前时间是凌晨
$hourBefore = floor($elapseTime / (60 * 60));
if ($hourBefore <= 9) {
return $hourBefore . ' 小时前';
} else {
return '昨天:' . date('H:i', $time);
}
} else {
return '昨天:' . date('H:i', $time);
}
}

return date('m-d H:i:s', $time);
}
?>
1
2
3
4
5
6
7
8
$today = new DateTime();
$today->setTime(23, 0, 0);

$t = new DateTime();
$t->modify('-1 year -1 day');
$t->setTime(1, 0, 0);

echo time2Readability($t->getTimestamp(), $today->getTimestamp());

参考:https://blog.csdn.net/technofiend/article/details/78627161