简体   繁体   English

使用JS将日期字符串转换为可读方式

[英]Convert date string to readable way using JS

I have stored RSS feed's published date "pubDate" in a JS string variable. 我已经将RSS feed的发布日期“ pubDate”存储在JS字符串变量中。 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. 现在,我需要以一种更易读的方式来显示它,例如在PrettyDate,MomentJS中显示“ 2秒前,5分钟前,一个小时前,5天前,一个月前,1年前”。 It should be light weight. 它应该重量轻。 And shouldn't use external JS plugins. 并且不应该使用外部JS插件。

I can change the initial date string using toGMTString(), toISOString(), toString() or toLocaleString(). 我可以使用toGMTString(),toISOString(),toString()或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 dtDate1 =“ 2013-10-21 13:45:06”;

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

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

alert('Difference in milliseconds : ' + nDifference); alert('以毫秒为单位的差异:'+ nDifference);

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

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

alert('time diff in sec : ' + Math.round(nDifference/1000)); alert('以秒为单位的时间差:'+ Math.round(nDifference / 1000));

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

There are a wide range of Javascript and Jquery libraries available if for handling date easily ! 如果可以轻松处理日期,则可以使用多种Javascript和Jquery库! 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/ 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. MomentJS是相当不错的lib,但是仍然像您所说的那样,它试图解决许多问题。 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. 最好的策略是先尝试使用它,然后再发现任何性能限制(在对ofc进行性能分析之后),然后可以尝试选择所需的部分。

This works best for me when I need something specific. 当我需要特定的东西时,这对我来说效果最好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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