/**
* 格式化时间 例如:parseTime(new Date(), '{y}-{m}-{d}'),
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string | null}
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null;
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
let date;
if (typeof time === 'object') {
date = time;
} else {
if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
time = parseInt(time);
}
if (typeof time === 'number' && time.toString().length === 10) {
time = time * 1000;
}
date = new Date(time);
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
};
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key];
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value];
}
return value.toString().padStart(2, '0');
});
return time_str;
}
/**
* 秒转换成hh:mm:ss格式
* @param {Number} seconds 秒
* @returns
*/
export function formatSeconds(seconds) {
let hh = parseInt(seconds / 3600, 10);
if (hh < 10) hh = `0${hh}`;
let mm = parseInt((seconds - hh * 3600) / 60, 10);
if (mm < 10) mm = `0${mm}`;
let ss = parseInt((seconds - hh * 3600) % 60, 10);
if (ss < 10) ss = `0${ss}`;
return `${hh}:${mm}:${ss}`;
}
/**
* 秒转换成h小时m分钟s秒格式
* @param {Number} seconds 秒
* @param {String} unit 转化单位 hour 小时 minute 分钟 unit 秒
* @param {Boolean} rounding 是否四舍五入 超过30
* @returns
*/
export function formatSeconds2(seconds, unit = 'second', rounding = false) {
if (seconds === 0) {
return unit === 'second' ? '0秒' : '0分钟';
}
let str = '';
let h = parseInt(seconds / 3600, 10);
let m = parseInt((seconds - h * 3600) / 60, 10);
const s = parseInt((seconds - h * 3600) % 60, 10);
if (unit === 'second') {
str = `${h > 0 ? `${h}小时` : ''}${m > 0 ? `${m}分钟` : ''}${s > 0 ? `${s}秒` : ''}`;
} else if (unit === 'minute') {
if (rounding && s >= 30) {
m += 1;
}
str = `${h > 0 ? `${h}小时` : ''}${m > 0 ? `${m}分钟` : ''}`;
} else {
if (rounding && m >= 30) {
h += 1;
}
str = `${h > 0 ? `${h}小时` : ''}`;
}
return str;
}