在项目中,我们经常会遇到需要对时间戳进行处理,下面分为几种情况进行说明:
(1)获取系统当前时间,并将其格式化 (eg. 2018-01-08)
var formatDate = function () { var date = new Date(); var y = date.getFullYear(); var m = date.getMonth() + 1; var d = date.getDate(); m = m < 10 ? ("0" + m) : m; d = d < 10 ? ("0" + d) : d; return y + "-" + m + "-" + d + " "; } formatDate();
(2)获取时间是周几(eg.周四)
let time=new Date(2018-01-02) let weekDay="星期" + "日一二三四五六".charAt(time.getDay()); console.log(weekDay) //星期四
(3)将两个时间戳的差值转化为具体的用时(eg.历时2.1周)
let seconds = 1000; let minute = seconds * 60; let hour = minute * 60; let day = hour * 24; let month = day * 30; let diffValue = 1245653280; let monthC = diffValue / month; let weekC = diffValue / (7 * day); let dayC = diffValue / day; let hourC = diffValue / hour; let minC = diffValue / minute; let secC = diffValue / seconds; if (monthC >= 1) { this.uTime = parseFloat(monthC.toFixed(1)) + "个月"; } else if (weekC >= 1) { this.uTime = parseFloat(weekC.toFixed(1)) + "周"; } else if (dayC >= 1) { this.uTime = parseFloat(dayC.toFixed(1)) + "天"; } else if (hourC >= 1) { this.uTime = parseFloat(hourC.toFixed(1)) + "小时"; } else if (minC >= 1) { this.uTime = parseFloat(minC.toFixed(1)) + "分钟"; } else { this.uTime = parseFloat(secC.toFixed(1)) + "秒"; }