module.exports = class TimeKit { static dateToTimestamp (str) { let [a, b] = str.split(' ') let [year, month, day] = a.split('/') let [hour, minute, second] = b.split(':') return new Date(year, month - 1, day, hour, minute, second).getTime() / 1000 } // 时间戳转换chart时间 static getTime (timestamp) { // 组织日期格式并返回 return this.dateFormat('YYYY-mm-dd HH:MM:SS:sss', new Date(timestamp * 1000)) } static dateFormat(fmt, date) { let ret; const opt = { "Y+": date.getFullYear().toString(), // 年 "m+": (date.getMonth() + 1).toString(), // 月 "d+": date.getDate().toString(), // 日 "H+": date.getHours().toString(), // 时 "M+": date.getMinutes().toString(), // 分 "S+": date.getSeconds().toString(), // 秒 "s+": date.getMilliseconds().toString() // 毫秒 // 有其他格式化字符需求可以继续添加,必须转化成字符串 }; for (let k in opt) { ret = new RegExp("(" + k + ")").exec(fmt); if (ret) { fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0"))) } } return fmt; } /** * 毫秒级时间戳转换 * * @param timestamp * @returns {*} */ static getTimeByMillisecond = function (timestamp) { // 组织日期格式并返回 return TimeKit.dateFormat('YYYY-mm-dd HH:MM:SS', new Date(timestamp)) } /** * 毫秒级时间戳转换,但只保留日期 * * @param timestamp * @returns {*} */ static getDateByMillisecond = function (timestamp) { // 组织日期格式并返回 return TimeKit.dateFormat('YYYY-mm-dd', new Date(timestamp)) } /** * 秒级时间戳转换 * * @param timestamp * @returns {*} */ static getTimeBySecond = function (timestamp) { // 组织日期格式并返回 return TimeKit.dateFormat('YYYY-mm-dd HH:MM:SS', new Date(timestamp * 1000)) } static sleep = function (time) { return new Promise(function (resolve) { setTimeout(function () { resolve(true) }, time) }) } }