Date.prototype.format = function(format = 'yy-mm-dd HH:ii:ss') {
var o = {
"y+": this.getFullYear(),
"m+": this.getMonth() + 1,
"d+": this.getDate(), //day
"x+": '日一二三四五六'.split('')[this.getDay()],
"H+": this.getHours(),
"h": (this.getHours()>12?'下午':'上午') + this.getHours()%12,
"i+": this.getMinutes(),
"s+": this.getSeconds(),
"S": this.getMilliseconds()
}
for (var k in o) {
var reg = new RegExp("(" + k + ")")
if (reg.test(format)) {
var v = o[k] + ''
if(v.length==1 && RegExp.$1.length < 4 && RegExp.$1.length > 1) v = '0' + v
format = format.replace(reg, v)
}
}
return format
}
Date.prototype.getNextMonth = function(gap = 1) {
const date = new Date(this.getFullYear(), this.getMonth() + gap)
return date
}
Date.prototype.getMonthEnd = function() {
return new Date(this.getNextMonth() - 1e3)
}
Date.prototype.getNextDay = function(gap = 1) {
const date = new Date(this.getFullYear(), this.getMonth(), this.getDate() + gap)
return date
}
Date.prototype.getToday = function() {
return this.format('yy-mm-dd 00:00:00').toDate()
}
Date.prototype.getDayEnd = function() {
return new Date(this.getToday()*1 + 86400e3 - 1e3)
}
Date.prototype.toISO8String = function() {
return this.format('y-m-d HH:ii:ss')
}
String.prototype.toDate = function() {
const arr = this.split(/\D+/);
if(arr.length < 2) return null;
for(const idx in arr) {
arr[idx] = arr[idx]*1
}
arr[1] = arr[1]*1 - 1;
return new Date(...arr)
}
String.prototype.toNiceTime = function(now, mode = 1) {
const date = this.toString().toDate()
// console.log(now, date)
const second = (now - date)/1e3 | 0
if((mode == 1 || mode == 11) && second > 0) {
if(second < 10) return '刚刚'
if(second < 60) return (second - second%10) + '秒前'
if(second < 60*60) return Math.floor(second/60) + '分钟前'
if(mode == 11) {
if(second < 86400) return Math.floor(second/3600) + '小时前'
return Math.floor(second/86400) + '天前'
}
}
let datePart = date.format('yy-mm-dd')
const timePart = date.format('HH:ii')
const today = now.format('y-m-d').toDate()
if(date.getFullYear() == now.getFullYear()) datePart = date.format('m月d日')
if(mode == 2) {
return datePart
}
if(second < 0) {
const nextDay = now.getNextDay()
if(date >= nextDay && date <= nextDay.getDayEnd()) datePart = '明天'
}
else if(date >= today) datePart = '今天'
else if(date >= today.getNextDay(-1)) datePart = '昨天'
return datePart + ' ' + timePart
}
String.prototype.cutStr = function(pre = 100, trail = 0) {
if(this.length <= pre + trail) return this
let txt = this.substr(0, pre) + '...'
if(trail) txt += this.substr(-trail)
return txt
}
Array.sortArrayBy = function(arr, key, isDesc) {
arr.sort((a, b) => {
return (isDesc ? -1 : 1) * (a[key] - b[key])
})
return arr
}
// Array.prototype.sortBy 遍历时需增加判断 arr.hasOwnProperty(key)
js时间-公共方法
最新推荐文章于 2021-12-15 18:51:56 发布