Calculate a timestamp from the current time, for example: years ago, months ago, days ago, hours ago, minutes ago, just now.

The output effect

Code:

function getDistanceDay(time) { let stime = new Date().getTime(); let usedTime = stime - time; // the number of milliseconds between two timestamps let one_minute = 60 * 1000; let one_hour = 60 * 60 * 1000; let one_day = 24 * 60 * 60 * 1000; let timeTxt = ''; If (disparityDay >= one_day) {// Let disparityDay = parseInt(disparitytime/one_day); Disparxt = disparityDay + 'days before '; If (disparityDay > getMonthDay()) timeTxt = getDisparityMonth(disparityDay) + 'disparityDay '; DisparityDay if (disparityDay > getYearDay()) timeTxt = parseInt(disparityDay/getYearDay()) + '前'; } else {if (usedTime >= one_hour) {timeTxt = parseInt(usedTime/one_hour); } else if (usedTime >= one_minute) {timeTxt = parseInt(usedTime/one_minute); } else {timeTxt = 'just '; } } return timeTxt; Function getDisparityMonth(disparityDay) {let disparityMonth = 0; let countFc = () => { if (disparityDay > getMonthDay(disparityMonth)) { disparityDay -= getMonthDay(disparityMonth) disparityMonth += 1; countFc(disparityMonth) } else { return disparityMonth; } } countFc(disparityMonth) return disparityMonth; Function getNowMonth() {return new Date().getMonth() + 1; } function getMonthDay(upNum) {let day = 0; let month = getNowMonth(); if (upNum) { let date = new Date(); date.setMonth(date.getMonth() - upNum); month = date.getMonth() + 1; } if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { day = 31 } else if (month == 2) { if (getYearDay() == 366) day = 29 if (getYearDay() == 365) day = 28 } else { day = 30 } return day; Function getYearDay() {let day = 365 let year = new Date().getFullYear(); if (year % 4 == 0) day = 366; return day } let time = (new Date().getTime()) - (1000 * 60 * 60 * 24 * 20) let timeTxt = getDistanceDay(time) console.log('timeTxt', timeTxt)Copy the code