PHP/Python/js/Golang/Java:时间转为人类可读的字符串格式:刚刚、几分钟前、几小时前、几天前

简介: PHP/Python/js/Golang/Java:时间转为人类可读的字符串格式:刚刚、几分钟前、几小时前、几天前

时间转换为为刚刚、几分钟前、几小时前、几天前,有两种思路:

例如

2000-01-01 23:00:00  (需要格式化的时间)
2000-01-02 01:00:00   (此刻)

1、按照天、时、分逐个比较:不看时分秒,就是1天前

2、按照时间戳毫秒之差:要看时分秒,就是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
    }
}


相关文章
|
7天前
|
JSON JavaScript 前端开发
在Python中调用和执行JavaScript
在Python中调用和执行JavaScript主要通过`PyExecJS`库实现。安装库后,可以使用`execjs.compile`编译JS代码并用`eval`或`call`执行。此外,还能加载JavaScript库和框架,调用外部JS文件,处理返回值,以及在两者间传递数据。Python和JavaScript各有优劣,适用于不同场景,结合使用可增强项目功能和灵活性。
24 0
|
9天前
|
Python
1167: 分离字符串(PYTHON)
1167: 分离字符串(PYTHON)
|
27天前
|
大数据 Python
使用Python查找字符串中包含的多个元素
本文介绍了Python中查找字符串子串的方法,从基础的`in`关键字到使用循环和条件判断处理多个子串,再到利用正则表达式`re模块`进行复杂模式匹配。文中通过实例展示了如何提取用户信息字符串中的用户名、邮箱和电话号码,并提出了优化策略,如预编译正则表达式和使用生成器处理大数据。
20 1
|
1月前
|
数据挖掘 开发者 Python
Python:字符串判断子串
Python:字符串判断子串
|
1月前
|
程序员 数据安全/隐私保护 Python
Python:翻转字符串
Python:翻转字符串
|
1月前
|
索引 Python
Python系列(14)—— 字符串运算符
Python系列(14)—— 字符串运算符
|
1月前
|
存储 自然语言处理 数据挖掘
Python:计算字符串中每个单词出现的次数
Python:计算字符串中每个单词出现的次数
|
1天前
|
数据采集 Python
python学习9-字符串
python学习9-字符串
|
9天前
|
Python
171: 字符串的倒序(python)
171: 字符串的倒序(python)
|
25天前
|
JSON C++ 数据格式
【Python 基础教程 08】全面入门到精通:Python3 字符串操作实战教程与深度指南
【Python 基础教程 08】全面入门到精通:Python3 字符串操作实战教程与深度指南
82 0