将数字四舍五入到指定的小数位数
将数字四舍五入到指定的小数位数。使用 Math.round() 和模板字面量将数字四舍五入为指定的小数位数。 省略第二个参数 decimals ,数字将被四舍五入到一个整数。
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
round(1.345, 2) // 1.35
round(1.345, 1) // 1.3
时间格式化
Helper.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
function dateFormat(date, fmt) {
var o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'q+': Math.floor((date.getMonth() + 3) / 3),
'S': date.getMilliseconds()
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt
}
xx个小时前发布
ios在对于new Date解析的时候存在问题,所以需要做一下处理new Date(time.replace(/-/g,’/‘)).getTime(),如下所以,以下参数格式 2019-4-45
function getDateDiffCountdown(time) {
let dateTimeStamp = new Date(time.replace(/-/g,'/')).getTime()
let result = time
let minute = 1000 * 60
let hour = minute * 60
let day = hour * 24
let month = day * 30
let now = new Date().getTime()
let diffValue = now - dateTimeStamp
if (diffValue < 0) return
var monthC = diffValue / month
let weekC = diffValue / (7 * day)
let dayC = diffValue / day
let hourC = diffValue / hour
let minC = diffValue / minute
if (monthC >= 1) {
return result
}
if (weekC >= 1) {
result = parseInt(weekC) + "周前"
return result;
}
if (dayC >= 1) {
result = parseInt(dayC) + "天前"
return result;
}
if (hourC >= 1) {
result = parseInt(hourC) + "小时前"
return result;
}
if (minC >= 1) {
result = parseInt(minC) + "分钟前"
return result
}
return "刚刚"
}
活动已经开始xx秒
getDateDiff(start, currentTime, 'second') // 活动已经开始xx秒
function getDateDiff(startTime, endTime, diffType) {
// 将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式
startTime = startTime.replace(/\-/g, '/')
endTime = endTime.replace(/\-/g, '/')
// 将计算间隔类性字符转换为小写
diffType = diffType.toLowerCase()
var sTime = new Date(startTime) // 开始时间
var eTime = new Date(endTime) // 结束时间
// 作为除数的数字
var divNum = 1
switch (diffType) {
case 'second':
divNum = 1000
break
case 'minute':
divNum = 1000 * 60
break
case 'hour':
divNum = 1000 * 3600
break
case 'day':
divNum = 1000 * 3600 * 24
break
default:
break
}
return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum))
}
时间格式倒计时
function getNextMondayDay() {
var Stamp;
Stamp = new Date();
var num = 7 - Stamp.getDay() + 1;
Stamp.setDate(Stamp.getDate() + num);
var year = Stamp.getFullYear(); //获取完整的年份(4位,1970-????)
var month = Stamp.getMonth() + 1; //获取当前月份(0-11,0代表1月)
var mvar = "";
if (month < 10) {
mvar = "0" + month;
} else {
mvar = month + "";
}
var day = Stamp.getDate();
var dvar = "";
if (day < 10) {
dvar = "0" + day;
} else {
dvar = day + "";
}
return mvar +"/"+ dvar +'/'+year + " 04:00"
}