3

论坛等发贴时间格式转换的正确姿势(n秒/n天)等

 1 month ago
source link: https://www.haorooms.com/post/bbs_time_publish_tsf
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

论坛等发贴时间格式转换的正确姿势(n秒/n天)等

2024年4月14日 1001次浏览

本篇文章基于今天早上,掘金给我推送了一篇文章(不清楚为啥突然给我推送这个),是关于时间转换的。看到这篇文章阅读量蛮大,留言挺多,很多小伙伴收藏了,因为很久很久之前,我们项目中也有类似的实现,简单看了一下这位小伙伴的实现,还是有一些问题。所以本篇文章纠正一下他的这些问题,帮助小伙伴在后面用到的时候能够使用准确的。而不是上线之后,会有很多问题反馈出来的那种。

掘金小伙伴的实现大概存在如下几个问题

1、时间没有转成固定区时时间,假如某人在国外,服务器在国内,国外的区时和国内不一致,很可能导致观看时间比发布时间还早的情况,所以要转换为固定时区来计算时间,例如,统一转换为服务器用的区时,例如:北京时间

2、几天前的逻辑不太对,应该以0点为准,假如今天是14号,你时间输入12号,打印的时间是1天前,肯定不对,

3、 new Date(date).getTime(),有些ios手机这么写解析不对,可以真机测试一下。应该说是兼容性问题吧

    // ios直接new Date(某个时间) 经常出现格式不对的情况,如下写法可以兼容
    function parseDateString(dateString) {
      const regex = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/
      const match = dateString.match(regex)

      if (match) {
        const year = parseInt(match[1])
        const month = parseInt(match[2]) - 1
        const day = parseInt(match[3])
        const hour = parseInt(match[4])
        const minute = parseInt(match[5])
        const second = parseInt(match[6])
        return new Date(year, month, day, hour, minute, second)
      }
      return new Date(dateString)
    }

   // 格式转换
    export const formatPublishTime = (createTime) => {
      if (!createTime) {
        return ''
      }
    // 统一转换为北京时间
      const currentTime = new Date(new Date().getTime() + (parseInt(new Date().getTimezoneOffset() / 60) + 8) * 3600 * 1000)
      const publishTime = parseDateString(createTime)

      const timeDiff = Math.floor((currentTime - publishTime) / 1000) // 计算时间差,单位为秒
     // 将时间转换为0点,0点为一天开始,符合人们平时的习惯
      const dayDiff = Math.floor((currentTime.setHours(0, 0, 0, 0) - publishTime.setHours(0, 0, 0, 0)) / 1000 / 60 / 60 / 24)
      if (dayDiff == 0) {
        if (timeDiff < 60) {
          return timeDiff + '秒前发布'
        } else if (timeDiff < 3600) {
          const minutes = Math.floor(timeDiff / 60)
          return minutes + '分钟前发布'
        } else {
          const hours = Math.floor(timeDiff / 3600)
          return hours + '小时前发布'
        }
      } else if (dayDiff == 1) {
        return '昨天发布'
      } else if (dayDiff == 2) {
        return '前天发布'
      } else {
        const year = publishTime.getFullYear()
        const month = ('0' + (publishTime.getMonth() + 1)).slice(-2)
        const day = ('0' + publishTime.getDate()).slice(-2)
        return year + '-' + month + '-' + day + '发布'
      }
    }

上面写法应该没有大问题了,希望看到之前收藏的小伙伴可以看下这篇文章,也希望这个问题给你有所帮助。今年是haorooms博客文章10年,10年经历了很多,博客仅仅是个人问题的一些记录。不过有点奢侈,自己搞了一个服务器来做。但是后面是否通过转型来获取博客服务器的费用支持,还有待考虑,希望我的博客可以长久的写下去!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK