代码之家  ›  专栏  ›  技术社区  ›  user7747472

如何将UNIX时间戳转换为相对日期,如whatsapp最后一次看到的状态和时刻。JS

  •  -1
  • user7747472  · 技术社区  · 4 年前

    我想将UNIX时间戳显示为最后一次看到的状态,就像WhatsApp在javascript中所做的那样。我正在使用 moment.js 据我所知,我们可以格式化日期或使用 .fromNow() 这给出了一个相对的日期,但不是我想要的。

    例如, 允许Unix时间戳:1606908420

    如果我使用 moment.unix(1606908420).formNow() 结果将是 few seconds ago 或类似的东西

    但我要找的是,它应该显示 Today 11:30 am .

    同样地

    For a date of yesterday, it should show: Yesterday 11:30 am
    For a date of day before yesterday, it should show: Mon 11:30 am
    
    Any date of last week or earlier, it should show 25-11-2020 
    

    有人能帮帮我吗?我怎样才能做到这一点?

    0 回复  |  直到 4 年前
        1
  •  0
  •   Abhishek Patel    4 年前

    将UNIX时间戳转换为日期

    1. 使用 toDate() 方法

      {new Date(timestamp?.toDate()).toUTCString()}

      Wed, 2 Dec 2020 12:00:00 GMT

    2. 使用 瞬间 方法

      {moment.unix(order.data.created).format("MMMM Do YYYY, h:mma")}

    我强烈推荐第二个 瞬间 为你。了解更多信息 moment docs

        2
  •  0
  •   Dhaya Sanjai    3 年前

    将Moment Date转换为类似于Whatsapp的格式

    //utility function to convert your date to looks like in whatsapp
    
    const dateFormatter = (date) => {
    
        //here we were subtracting our date from current time which will be in milliseconds
        const dateDifferenceInTime =
            new Date().getTime() - new Date(date.toDate()).getTime();
    
        // conerting milli seconds to days
        // (1000 milliseconds * (60 seconds * 60 minutes) * 24 hours)
        const dateDifferenceInDays =
            dateDifferenceInTime / (1000 * 60 * 60 * 24);
    
        //After returning in particular formats as of our convinent
        if (dateDifferenceInDays < 1) {
            return moment(date.toDate()).format("LT");// 10:04 am
        } else if (dateDifferenceInDays < 2) {
            return "Yesterday"; // just YesterDay
        } else if (dateDifferenceInDays <= 7) {
            return moment(date.toDate()).format("dddd");//like monday , tuesday , wednesday ....
        } else {
            return moment(date.toDate()).format("l");// if it was more than a week before it will returns as like 05/23/2022
        }
    };
    
    推荐文章