Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

javascript - 如何格式化从xxx开始的时间,例如“ 4分钟前”,类似于Stack Exchange网站(How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites)

The question is how to format a JavaScript Date as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.

(问题是如何将JavaScript Date格式化为字符串,以说明经过的时间,类似于您看到Stack Overflow上显示的时间的方式。)

eg

(例如)

  • 1 minute ago

    (1分钟前)

  • 1 hour ago

    (1小时前)

  • 1 day ago

    (1天前)

  • 1 month ago

    (1个月前)

  • 1 year ago

    (1年以前)

  ask by Sky Sanders translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

 function timeSince(date) { var seconds = Math.floor((new Date() - date) / 1000); var interval = Math.floor(seconds / 31536000); if (interval > 1) { return interval + " years"; } interval = Math.floor(seconds / 2592000); if (interval > 1) { return interval + " months"; } interval = Math.floor(seconds / 86400); if (interval > 1) { return interval + " days"; } interval = Math.floor(seconds / 3600); if (interval > 1) { return interval + " hours"; } interval = Math.floor(seconds / 60); if (interval > 1) { return interval + " minutes"; } return Math.floor(seconds) + " seconds"; } var aDay = 24*60*60*1000 console.log(timeSince(new Date(Date.now()-aDay))); console.log(timeSince(new Date(Date.now()-aDay*2))); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...