JS把指定日期转换为几秒前、几小时前等格式, 转换后的时间可读性更强。
Date.prototype.toRelativeTime = function(now_threshold) { var delta = new Date() - this; now_threshold = parseInt(now_threshold, 10); if (isNaN(now_threshold)) { now_threshold = 0; } if (delta <= now_threshold) { return '刚刚'; } var units = null; var conversions = { '毫秒': 1, // ms -> ms '秒': 1000, // ms -> sec '分钟': 60, // sec -> min '小时': 60, // min -> hour '天': 24, // hour -> day '月': 30, // day -> month (roughly) '年': 12 // month -> year }; for (var key in conversions) { if (delta < conversions[key]) { break; } else { units = key; // keeps track of the selected key over the iteration delta = delta / conversions[key]; } } // pluralize a unit when the difference is greater than 1. delta = Math.floor(delta); return [delta, units].join(" "); };
示例代码:
var d = new Date('2015-01-04 08:09:00'); alert(d.toRelativeTime()+'之前');
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10004.html