time-kit.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 getDateByMillisecond = function (timestamp) {
  50. // 组织日期格式并返回
  51. return TimeKit.dateFormat('YYYY-mm-dd', new Date(timestamp))
  52. }
  53. /**
  54. * 秒级时间戳转换
  55. *
  56. * @param timestamp
  57. * @returns {*}
  58. */
  59. static getTimeBySecond = function (timestamp) {
  60. // 组织日期格式并返回
  61. return TimeKit.dateFormat('YYYY-mm-dd HH:MM:SS', new Date(timestamp * 1000))
  62. }
  63. static sleep = function (time) {
  64. return new Promise(function (resolve) {
  65. setTimeout(function () {
  66. resolve(true)
  67. }, time)
  68. })
  69. }
  70. }