将时间转换为为刚刚、几分钟前、几小时前、几天前,有两种思路:
例如
2000-01-01 23:00:00 (需要格式化的时间)
2000-01-02 01:00:00 (此刻)
1天前2小时前
为了更精确,本例采用 方式2:按照时间戳毫秒之差 的思路实现
PHP 代码实现
<?php
/**
* @param $time_value int|string 时间戳
* @return false|string
*
* 时间格式化为:
* 刚刚
* 1分钟前-56分钟前
* 1小时前-23小时前
* 1天前-7天前
* 2022-10-09 13:33
*/
function timeForHuman($time_value)
{
// 兼容传入字符串
if (is_string($time_value)) {
$time_value = strtotime($time_value);
}
$second = 1;
$minute = $second * 60;
$hour = $minute * 60;
$day = $hour * 24;
$day_8 = $day * 8;
$now_time = time();
$duration = $now_time - $time_value;
if ($duration < $minute) {
return '刚刚';
} else if ($duration < $hour) {
return floor($duration / $minute) . '分钟前';
} elseif ($duration < $day) {
return floor($duration / $hour) . '小时前';
} else if ($duration < $day_8) {
return floor($duration / $day) . '天前';
} else {
return date("Y-m-d H:i", $time_value);
}
}
测试示例
$now_time = time();
$now_str = date('Y-m-d H:i:s', $now_time);
echo $now_time . PHP_EOL;
// 1665381270
echo $now_str . PHP_EOL;
// 2022-10-10 13:54:30
echo timeForHuman($now_time) . PHP_EOL;
// 刚刚
echo timeForHuman($now_str) . PHP_EOL;
// 刚刚
echo timeForHuman('2022-10-10 13:33:11') . PHP_EOL;
// 21分钟前
JavaScript实现版本
/**
* 格式化时间为人类可读的字符串格式
* @param {number|string|Date} time_value 13位时间戳
* @returns {string}
*
* 时间格式化为:
* 刚刚
* 1分钟前-56分钟前
* 1小时前-23小时前
* 1天前-7天前
* 2022-10-09 13:33
*/
function timeForHuman(time_value) {
// 兼容其他类型的参数
if (typeof time_value != 'number') {
time_value = Date.parse(time_value)
}
// 进制转换
let millisecond = 1
let second = millisecond * 1000
let minute = second * 60
let hour = minute * 60
let day = hour * 24
let day_8 = day * 8
now_time = Date.now()
duration = now_time - time_value
if (duration < minute) {
return '刚刚'
} else if (duration < hour) {
return Math.floor(duration / minute) + '分钟前'
} else if (duration < day) {
return Math.floor(duration / hour) + '小时前'
} else if (duration < day_8) {
return Math.floor(duration / day) + '天前'
} else {
let date = new Date(time_value)
return [
[
date.getFullYear(),
('0' + (date.getMonth() + 1)).slice(-2),
('0' + date.getDate()).slice(-2),
].join('-'),
[
('0' + date.getHours()).slice(-2),
('0' + date.getMinutes()).slice(-2),
].join(':'),
].join(' ')
}
}
测试
console.log(new Date());
// 2022-10-12T02:45:06.286Z
console.log(timeForHuman(new Date()))
// 刚刚
console.log(timeForHuman(1635476685643))
// 2021-10-29 11:04
console.log(timeForHuman('2021-10-29T03:04:45.640Z'))
// 2021-10-29 11:04
console.log(timeForHuman('2022-10-12'))
// 2小时前
Python实现版本
import time
from datetime import datetime
import math
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
DATETIME_SHORT_FORMAT = "%Y-%m-%d %H:%M"
def time_for_human(time_value):
"""
格式化时间为人类可读的字符串格式
:param time_value: {int|string|datetime} time_value 10位时间戳
:return: string
时间格式化为:
刚刚
1分钟前-56分钟前
1小时前-23小时前
1天前-7天前
2022-10-09 13:33
"""
second = 1
minute = second * 60
hour = minute * 60
day = hour * 24
day_8 = day * 8
if isinstance(time_value, datetime):
time_value = time_value.timestamp()
if isinstance(time_value, str):
time_value = time.mktime(time.strptime(time_value, DATETIME_FORMAT))
now_time = int(time.time())
duration = now_time - time_value
if duration < minute:
return '刚刚'
elif duration < hour:
return str(math.floor(duration / minute)) + '分钟前'
elif duration < day:
return str(math.floor(duration / hour)) + '小时前'
elif duration < day_8:
return str(math.floor(duration / day)) + '天前'
else:
return time.strftime(DATETIME_SHORT_FORMAT, time.localtime(time_value))
示例
print(time_for_human(1665381270))
# 2天前
print(time_for_human(datetime.now()))
# 刚刚
print(time_for_human(time.time() - 100))
# 1分钟前
print(time_for_human('2022-10-10 13:33:11'))
# 2天前
Golang代码实现
package timeutil
import (
"fmt"
"time"
)
// 格式化
const DATE_LAYOUT = "2006-01-02"
// 以秒为基本单位的时间枚举常量
const (
SECOND = 1
MINUTE = SECOND * 60
HOUR = MINUTE * 60
DAY = HOUR * 24
DAY_8 = DAY * 8
)
/**
* 格式化日期
* timeValue 10位时间戳
*/
func TimeForHuman(timeValue int64) string {
nowTime := time.Now().Unix()
diffTime := nowTime - timeValue
if diffTime <= MINUTE {
return "刚刚"
} else if diffTime < HOUR {
return fmt.Sprintf("%d分钟前", int(diffTime/MINUTE))
} else if diffTime <= DAY {
return fmt.Sprintf("%d小时前", int(diffTime/HOUR))
} else if diffTime <= DAY_8 {
return fmt.Sprintf("%d天前", int(diffTime/DAY))
} else {
return time.Unix(timeValue, 0).Format(DATE_LAYOUT)
}
}
测试代码
package timeutil
import (
"fmt"
"testing"
"time"
)
func TestTimeForHuman(t *testing.T) {
ret1 := TimeForHuman(time.Now().Unix() - 3*SECOND)
fmt.Println(ret1)
ret2 := TimeForHuman(time.Now().Unix() - 3*MINUTE)
fmt.Println(ret2)
ret3 := TimeForHuman(time.Now().Unix() - 3*HOUR)
fmt.Println(ret3)
ret4 := TimeForHuman(time.Now().Unix() - 3*DAY)
fmt.Println(ret4)
ret5 := TimeForHuman(time.Now().Unix() - 3*DAY_8)
fmt.Println(ret5)
}
输出
$ go test
刚刚
3分钟前
3小时前
3天前
2023-01-23
PASS
ok timeutil 0.005s
Java代码实现
package com.example;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeUtil {
public final static long SECOND = 1000;
public final static long MINUTE = SECOND * 60;
public final static long HOUR = MINUTE * 60;
public final static long DAY = HOUR * 24;
/**
* 将13位时间戳转为人类可读的字符串形式
*
* @param timeValue 将13位时间戳
* @return
*/
public static String timeForHuman(long timeValue) {
long now = System.currentTimeMillis();
long duration = now - timeValue;
if (duration <= MINUTE) {
return "刚刚";
} else if (duration < HOUR) {
return String.format("%d分钟前", (int) (duration / MINUTE));
} else if (duration < DAY) {
return String.format("%d小时前", (int) (duration / HOUR));
} else if (duration < DAY * 8) {
return String.format("%d天前", (int) (duration / DAY));
} else {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(new Date(timeValue));
}
}
}
测试
package com.example;
import org.junit.Test;
public class TimeUtilTests {
@Test
public void timeForHuman() {
long now = System.currentTimeMillis();
String ret1 = TimeUtil.timeForHuman(now - 3 * TimeUtil.SECOND);
System.out.println(ret1);
// 刚刚
String ret2 = TimeUtil.timeForHuman(now - 3 * TimeUtil.MINUTE);
System.out.println(ret2);
// 3分钟前
String ret3 = TimeUtil.timeForHuman(now - 3 * TimeUtil.HOUR);
System.out.println(ret3);
// 3小时前
String ret4 = TimeUtil.timeForHuman(now - 3 * TimeUtil.DAY);
System.out.println(ret4);
// 3天前
String ret5 = TimeUtil.timeForHuman(now - 8 * TimeUtil.DAY);
System.out.println(ret5);
// 2023-02-08
}
}