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
    }
}


相关文章
|
10月前
|
SQL JSON Java
告别字符串拼接:用Java文本块优雅处理多行字符串
告别字符串拼接:用Java文本块优雅处理多行字符串
615 108
|
SQL 自然语言处理 数据库
【Azure Developer】分享两段Python代码处理表格(CSV格式)数据 : 根据每列的内容生成SQL语句
本文介绍了使用Python Pandas处理数据收集任务中格式不统一的问题。针对两种情况:服务名对应多人拥有状态(1/0表示),以及服务名与人名重复列的情况,分别采用双层for循环和字典数据结构实现数据转换,最终生成Name对应的Services列表(逗号分隔)。此方法高效解决大量数据的人工处理难题,减少错误并提升效率。文中附带代码示例及执行结果截图,便于理解和实践。
365 5
|
12月前
|
SQL JSON Java
告别拼接噩梦:Java文本块让多行字符串更优雅
告别拼接噩梦:Java文本块让多行字符串更优雅
946 82
|
10月前
|
消息中间件 人工智能 Java
抖音微信爆款小游戏大全:免费休闲/竞技/益智/PHP+Java全筏开源开发
本文基于2025年最新行业数据,深入解析抖音/微信爆款小游戏的开发逻辑,重点讲解PHP+Java双引擎架构实战,涵盖技术选型、架构设计、性能优化与开源生态,提供完整开源工具链,助力开发者从理论到落地打造高留存、高并发的小游戏产品。
|
11月前
|
Go 调度 Python
Golang协程和Python协程用法上的那些“不一样”
本文对比了 Python 和 Go 语言中协程的区别,重点分析了调度机制和执行方式的不同。Go 的协程(goroutine)由运行时自动调度,启动后立即执行;而 Python 协程需通过 await 显式调度,依赖事件循环。文中通过代码示例展示了两种协程的实际运行效果。
413 7
|
10月前
|
存储 小程序 Java
热门小程序源码合集:微信抖音小程序源码支持PHP/Java/uni-app完整项目实践指南
小程序已成为企业获客与开发者创业的重要载体。本文详解PHP、Java、uni-app三大技术栈在电商、工具、服务类小程序中的源码应用,提供从开发到部署的全流程指南,并分享选型避坑与商业化落地策略,助力开发者高效构建稳定可扩展项目。
|
12月前
|
自然语言处理 Java Apache
在Java中将String字符串转换为算术表达式并计算
具体的实现逻辑需要填写在 `Tokenizer`和 `ExpressionParser`类中,这里只提供了大概的框架。在实际实现时 `Tokenizer`应该提供分词逻辑,把输入的字符串转换成Token序列。而 `ExpressionParser`应当通过递归下降的方式依次解析
507 14
|
12月前
|
JavaScript Java Go
Go、Node.js、Python、PHP、Java五种语言的直播推流RTMP协议技术实施方案和思路-优雅草卓伊凡
Go、Node.js、Python、PHP、Java五种语言的直播推流RTMP协议技术实施方案和思路-优雅草卓伊凡
850 0
|
存储 缓存 安全
Java字符串缓冲区
字符串缓冲区是用于处理可变字符串的容器,Java中提供了`StringBuffer`和`StringBuilder`两种实现。由于`String`类不可变,当需要频繁修改字符串时,使用缓冲区更高效。`StringBuffer`是一个线程安全的容器,支持动态扩展、任意类型数据转为字符串存储,并提供多种操作方法(如`append`、`insert`、`delete`等)。通过这些方法,可以方便地对字符串进行添加、插入、删除等操作,最终将结果转换为字符串。示例代码展示了如何创建缓冲区对象并调用相关方法完成字符串操作。
374 13