time-kit.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. module.exports = class TimeKit {
  2. static dateToTimestamp (str) {
  3. let [a, b] = str.split(' ')
  4. let [year, month, day] = a.split('/')
  5. let [hour, minute, second] = b.split(':')
  6. return new Date(year, month - 1, day, hour, minute, second).getTime() / 1000
  7. }
  8. // 时间戳转换chart时间
  9. static getTime (timestamp) {
  10. // 组织日期格式并返回
  11. return this.dateFormat('YYYY-mm-dd HH:MM:SS:sss', new Date(timestamp * 1000))
  12. }
  13. static dateFormat(fmt, date) {
  14. let ret;
  15. const opt = {
  16. "Y+": date.getFullYear().toString(), // 年
  17. "m+": (date.getMonth() + 1).toString(), // 月
  18. "d+": date.getDate().toString(), // 日
  19. "H+": date.getHours().toString(), // 时
  20. "M+": date.getMinutes().toString(), // 分
  21. "S+": date.getSeconds().toString(), // 秒
  22. "s+": date.getMilliseconds().toString() // 毫秒
  23. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  24. };
  25. for (let k in opt) {
  26. ret = new RegExp("(" + k + ")").exec(fmt);
  27. if (ret) {
  28. fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
  29. }
  30. }
  31. return fmt;
  32. }
  33. /**
  34. * 豪秒级时间戳转换
  35. *
  36. * @param timestamp
  37. * @returns {*}
  38. */
  39. static getTimeByMillisecond = function (timestamp) {
  40. // 组织日期格式并返回
  41. return TimeKit.dateFormat('YYYY-mm-dd HH:MM:SS', new Date(timestamp))
  42. }
  43. /**
  44. * 秒级时间戳转换
  45. *
  46. * @param timestamp
  47. * @returns {*}
  48. */
  49. static getTimeBySecond = function (timestamp) {
  50. // 组织日期格式并返回
  51. return TimeKit.dateFormat('YYYY-mm-dd HH:MM:SS', new Date(timestamp * 1000))
  52. }
  53. static sleep = function (time) {
  54. return new Promise(function (resolve) {
  55. setTimeout(function () {
  56. resolve(true)
  57. }, time)
  58. })
  59. }
  60. }