300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 时间戳显示为多少分钟前 多少天前的JS处理 JS时间格式化 时间戳的转换

时间戳显示为多少分钟前 多少天前的JS处理 JS时间格式化 时间戳的转换

时间:2019-02-07 11:41:13

相关推荐

时间戳显示为多少分钟前 多少天前的JS处理 JS时间格式化 时间戳的转换

var dateDiff = function (timestamp) {// 补全为13位var arrTimestamp = (timestamp + '').split('');for (var start = 0; start < 13; start++) {if (!arrTimestamp[start]) {arrTimestamp[start] = '0';}}timestamp = arrTimestamp.join('') * 1;var minute = 1000 * 60;var hour = minute * 60;var day = hour * 24;var halfamonth = day * 15;var month = day * 30;var now = new Date().getTime();var diffValue = now - timestamp;// 如果本地时间反而小于变量时间if (diffValue < 0) {return '不久前';}// 计算差异时间的量级var monthC = diffValue / month;var weekC = diffValue / (7 * day);var dayC = diffValue / day;var hourC = diffValue / hour;var minC = diffValue / minute;// 数值补0方法var zero = function (value) {if (value < 10) {return '0' + value;}return value;};// 使用if (monthC > 4) {// 超过1年,直接显示年月日return (function () {var date = new Date(timestamp);return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';})();} else if (monthC >= 1) {return parseInt(monthC) + "月前";} else if (weekC >= 1) {return parseInt(weekC) + "周前";} else if (dayC >= 1) {return parseInt(dayC) + "天前";} else if (hourC >= 1) {return parseInt(hourC) + "小时前";} else if (minC >= 1) {return parseInt(minC) + "分钟前";}return '刚刚';};console.log(dateDiff(1560387311)); // 09月19日console.log(dateDiff(1560400790)); // 9月前console.log(dateDiff(1550062750)); // 2月前console.log(dateDiff(1547384350)); // 3周前console.log(dateDiff(1505283100802)); // 1分钟前

JS时间格式化,时间戳的转换

//时间转时间戳//将Thu Sep 20 16:47:52 GMT+0800 (中国标准时间)转换为1537433272051console.log(Date.parse(new Date()))console.log(new Date().getTime())

//将"-09-20 16:50:48"转换为1537433448000var timeDate = "-09-20 16:50:48";var Time = new Date(timeDate);var timestemp = Time.getTime();console.log(timestemp)

Date.parse() :时间字符串可以直接Date.parse(datestring),不需要new Date()Date.getTime() :需要将时间字符串先new Date(),再使用Date.getTime()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。