简体   繁体   中英

Convert date string to readable way using JS

I have stored RSS feed's published date "pubDate" in a JS string variable. Now I need to show it in a more readable way like "2 seconds ago, 5 minutes ago, an hour ago, 5 days ago, a month ago, 1 year ago" like in PrettyDate, MomentJS. It should be light weight. And shouldn't use external JS plugins.

I can change the initial date string using toGMTString(), toISOString(), toString() or toLocaleString(). How can I do this?

May be this help u out, use it acc. to ur req. :

var dtDate1 = "2013-10-21 13:45:06";

var dtDate2 = dtDate1.replace(/-/g,'/');

var nDifference = Math.abs(new Date() - new Date(dtDate2));

alert('Difference in milliseconds : ' + nDifference);

alert('time diff in hr : ' + Math.round(nDifference/3600000));

alert('time diff in min : ' + Math.round(nDifference/60000));

alert('time diff in sec : ' + Math.round(nDifference/1000));

alert('Difference in days : ' + Math.round(nDifference/86400000));

There are a wide range of Javascript and Jquery libraries available if for handling date easily ! So I would suggest you to go for that only as it would make your work a bit easier. You can refer this link for a list available libraries :

http://codegeekz.com/6-javascript-date-libraries-for-developers/

how much lightweight do you need ?

MomentJS is pretty good lib but still like you said, it tries to solve many problems. The best strategy is trying to use it first, then if you find any performance throttle ( after profiling ofc ), then you can try to pick the part you need.

This works best for me when I need something specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM