datetime.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // 格式化毫秒数为"年-月-日 时:分:秒"格式
  2. const formatDateTime = function(time) {
  3. const DATETIME = new Date(time);
  4. const year = DATETIME.getFullYear();
  5. const month = (DATETIME.getMonth() + 1) <= 9 ? "0" + (DATETIME.getMonth() + 1) : DATETIME
  6. .getMonth() + 1;
  7. const date = DATETIME.getDate() <= 9 ? "0" + DATETIME.getDate() : DATETIME.getDate();
  8. const hours = DATETIME.getHours() <= 9 ? "0" + DATETIME.getHours() : DATETIME.getHours();
  9. const minutes = DATETIME.getMinutes() <= 9 ? "0" + DATETIME.getMinutes() : DATETIME.getMinutes();
  10. const seconds = DATETIME.getSeconds() <= 9 ? "0" + DATETIME.getSeconds() : DATETIME.getSeconds();
  11. return year + '-' + month + '-' + date + " " + hours + ":" + minutes + ":" + seconds;
  12. }
  13. const formatDate = function(time) {
  14. const DATETIME = new Date(time);
  15. const year = DATETIME.getFullYear();
  16. const month = (DATETIME.getMonth() + 1) <= 9 ? "0" + (DATETIME.getMonth() + 1) : DATETIME
  17. .getMonth() + 1;
  18. const date = DATETIME.getDate() <= 9 ? "0" + DATETIME.getDate() : DATETIME.getDate();
  19. return year + '-' + month + '-' + date;
  20. }
  21. // 日期格式化
  22. const parseTime = function(time, pattern) {
  23. if (arguments.length === 0 || !time) {
  24. return null
  25. }
  26. const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  27. let date
  28. if (typeof time === 'object') {
  29. date = time
  30. } else {
  31. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  32. time = parseInt(time)
  33. } else if (typeof time === 'string') {
  34. time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm),'');
  35. }
  36. if ((typeof time === 'number') && (time.toString().length === 10)) {
  37. time = time * 1000
  38. }
  39. date = new Date(time)
  40. }
  41. const formatObj = {
  42. y: date.getFullYear(),
  43. m: date.getMonth() + 1,
  44. d: date.getDate(),
  45. h: date.getHours(),
  46. i: date.getMinutes(),
  47. s: date.getSeconds(),
  48. a: date.getDay()
  49. }
  50. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  51. let value = formatObj[key]
  52. // Note: getDay() returns 0 on Sunday
  53. if (key === 'a') {
  54. return ['日', '一', '二', '三', '四', '五', '六'][value]
  55. }
  56. if (result.length > 0 && value < 10) {
  57. value = '0' + value
  58. }
  59. return value || 0
  60. })
  61. return time_str
  62. }
  63. export {
  64. formatDateTime,
  65. formatDate,
  66. parseTime
  67. };