time-kit.js 1.9 KB

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