utils.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * 时间格式化
  3. * @param {String} time
  4. * @param {String} cFormat
  5. */
  6. export function parseTime(time, cFormat) {
  7. if (arguments.length === 0) {
  8. return null
  9. }
  10. if (!time) return ''
  11. /* 修复IOS系统上面的时间不兼容*/
  12. if (time.toString().indexOf('-') > 0) {
  13. time = time.replace(/-/g, '/')
  14. }
  15. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  16. let date
  17. if (typeof time === 'object') {
  18. date = time
  19. } else {
  20. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  21. time = parseInt(time)
  22. }
  23. if ((typeof time === 'number') && (time.toString().length === 10)) {
  24. time = time * 1000
  25. }
  26. date = new Date(time)
  27. }
  28. const formatObj = {
  29. y: date.getFullYear(),
  30. m: date.getMonth() + 1,
  31. d: date.getDate(),
  32. h: date.getHours(),
  33. i: date.getMinutes(),
  34. s: date.getSeconds(),
  35. a: date.getDay()
  36. }
  37. const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
  38. const value = formatObj[key]
  39. // Note: getDay() returns 0 on Sunday
  40. if (key === 'a') {
  41. return ['日', '一', '二', '三', '四', '五', '六'][value]
  42. }
  43. return value.toString().padStart(2, '0')
  44. })
  45. return time_str
  46. }
  47. /**
  48. * This is just a simple version of deep copy
  49. * Has a lot of edge cases bug
  50. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  51. * @param {Object} source
  52. * @returns {Object}
  53. */
  54. export function deepClone(source) {
  55. if (!source && typeof source !== 'object') {
  56. throw new Error('error arguments', 'deepClone')
  57. }
  58. const targetObj = Object.prototype.toString.call(source) === "[object Array]" ? [] : {}
  59. Object.keys(source).forEach(keys => {
  60. if (source[keys] && typeof source[keys] === 'object') {
  61. targetObj[keys] = deepClone(source[keys])
  62. } else {
  63. targetObj[keys] = source[keys]
  64. }
  65. })
  66. return targetObj
  67. }