javascript汇总
1.剩余时间格式化
/**
* 剩余时间格式化
*
* @export
* @param {number} times //传入毫秒
* @param {string} [format='H:F:S'] // 大写自动补全十位
* @returns string
*/
//小于10时,转化为01,02等
export function formatNum(n) {
return n * 1 < 10 ? `0${n}` : n;
}
export function formatCountDown(times, format = 'H:F:S') {
if (!times) return '';
let time = parseInt(times * 0.001, 10);
const seconds = time % 60;
time = parseInt(time / 60, 10);
const minutes = time % 60;
time = parseInt(time / 60, 10);
const hours = parseInt(time % 24, 10);
const days = parseInt(time / 24, 10);
return format.replace(/Y|y|M|m|D|d|H|h|F|f|S|s/g, function(a) {
switch (a) {
case 'd':
return days;
case 'D':
return formatNum(days);
case 'h':
return hours;
case 'H':
return formatNum(hours);
case 'f':
return minutes;
case 'F':
return formatNum(minutes);
case 's':
return seconds;
case 'S':
return formatNum(seconds);
}
});
}
2.格式化时间戳
export function formatDate(date, format = 'Y年M月D日') {
if (date === '' || date == null) return '';
if (!date) return '';
switch (typeof date) {
case 'string':
date = new Date(date.replace(/-/g, '/'));
break;
case 'number': {
let str = date + '';
if (str.length === 10) {
date = date * 1000;
}
date = new Date(date);
break;
}
default:
// do nothing...
}
if (!(date instanceof Date)) return;
return format.replace(/Y|y|M|m|D|d|H|h|F|f|S|s/g, function(a) {
switch (a) {
case 'y':
return (date.getFullYear() + '').slice(2);
case 'Y':
return date.getFullYear();
case 'm':
return date.getMonth() + 1;
case 'M':
return formatNum(date.getMonth() + 1);
case 'd':
return date.getDate();
case 'D':
return formatNum(date.getDate());
case 'h':
return date.getHours();
case 'H':
return formatNum(date.getHours());
case 'f':
return date.getMinutes();
case 'F':
return formatNum(date.getMinutes());
case 's':
return date.getSeconds();
case 'S':
return formatNum(date.getSeconds());
}
});
}
3.获取当前时间戳
export function timeStamp(date) {
if (date) {
if (typeof date === 'object') {
return Date.parse(date) / 1000;
} else {
return Date.parse(new Date(date)) / 1000;
}
} else {
return Date.parse(new Date()) / 1000;
}
}
4.获取时间戳的周
export function getWeek(value, type = 1) {
if (value) return '';
const tempDate = new Date(value);
let tempArray = ['日', '一', '二', '三', '四', '五', '六'];
if (type === 1) {
tempArray = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
}
return tempArray[tempDate.getDay()];
}
5.获取当天0点时间
export function getTimesmorning(date) {
if (!date) return '';
return new Date(date).setHours(0, 0, 0, 0);
}
6.获取24点时间
export function getTimesnight(date) {
if (!date) return '';
return new Date(date).setHours(24, 0, 0, 0);
}