Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the time representation from the past to the present by js

Shulou Source: shulou.com Published: 2022-06-01 04:35:43 09月25日 Update

This article mainly shows you "how js realizes the time representation from the past to the present". The content is simple and easy to understand and clearly organized. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "how js realizes the time representation from the past to the present".

Distance from past to present time

Sometimes we need to print the date 6 minutes ago, but don't want a large library to complete it. Here's a short clip that does just that:

const fromAgo = (date) => { const ms = Date.now() - date.getTime(); const seconds = Math.round(ms / 1000); const minutes = Math.round(ms / 60000); const hours = Math.round(ms / 3600000); const days = Math.round(ms / 86400000); const months = Math.round(ms / 2592000000); const years = Math.round(ms / 31104000000); switch (true) { case seconds < 60: return `${seconds} second(s) ago"`; case minutes < 60: return `${minutes} minute(s) ago"`; case hours < 24: return `${hours} hour(s) ago"`; case days < 30: return `${days} day(s) ago`; case months < 12: return `${months} month(s) ago`; default: return `${years} year(s) ago`; }};const createdAt = new Date(2021, 0, 5);fromAgo(createdAt); // 14 day(s) ago; above is "js how to achieve distance from the past to the present time expression" All the content of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Tags: Present tense content articles learning help great date easy to understand more organization fragments knowledge editing industry information information channels channels research Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Huawei Docker Shulou Information Xiaomi