nodejs-tool
Version:
74 lines (47 loc) • 2.62 kB
JavaScript
class UtilTool {
constructor() {
this.name = "UtilTool";
}
/**
* @name Sleep
* @description 一个同步方法,调用时方法时需要在方法前加 await 关键字,并且要在同步方法中
* @param {String} ms 睡眠时长,单位为毫秒
* @returns
*/
Sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* @name GetDate
* @description 获取一个格式化的日期
* @param {String} date 日期对象,默认为调用时的日期
* @param {String} format 格式化格式: 'year'、'month'、'day'、'hour'、'minute'、'second'、'YMD'、'hms'、'MD、'hm'、'MDhm'
* @param {String} separator_YMD 年月日的分割符
* @param {String} separator_hms 时分秒的分割符
* @param {String} separator 年月日和时分秒之间的分割符
* @returns
*/
GetDate = ({ date = new Date(), format = "", separator_YMD = "-", separator_hms = ":", separator = " " }) => {
process.env.TZ = 'Asia/Shanghai';
const datetime = new Date(date);
const year = String(datetime.getFullYear());
const month = String(datetime.getMonth() + 1).length > 1 ? String(datetime.getMonth() + 1) : '0' + (datetime.getMonth() + 1);
const day = String(datetime.getDate()).length > 1 ? String(datetime.getDate()) : '0' + datetime.getDate();
const hour = String(datetime.getHours()).length > 1 ? String(datetime.getHours()) : '0' + datetime.getHours();
const minute = String(datetime.getMinutes()).length > 1 ? String(datetime.getMinutes()) : '0' + datetime.getMinutes();
const second = String(datetime.getSeconds()).length > 1 ? String(datetime.getSeconds()) : '0' + datetime.getSeconds();
if (format === 'year') { return year; }
if (format === 'month') { return month; }
if (format === 'day') { return day; }
if (format === 'hour') { return hour; }
if (format === 'minute') { return minute; }
if (format === 'second') { return second; }
if (format === 'YMD') { return `${year}${separator_YMD}${month}${separator_YMD}${day}`; }
if (format === 'hms') { return `${hour}${separator_hms}${minute}${separator_hms}${second}`; }
if (format === 'MD') { return `${month}${separator_YMD}${day}`; }
if (format === 'hm') { return `${hour}${separator_hms}${minute}`; }
if (format === 'MDhm') { return `${month}${separator_YMD}${day}${separator}${hour}${separator_hms}${minute}`; }
return `${year}${separator_YMD}${month}${separator_YMD}${day}${separator}${hour}${separator_hms}${minute}${separator_hms}${second}`;
};
}
module.exports = UtilTool;