format.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. const format = {}
  2. /**@dateTimeFliter 转换格林日期时间格式为常用日期格式
  3. * @time[必填] Date 格林日期格式
  4. * @part[可选,默认:0] Number 选择返回日期时间部分 列:0:返回所有 1:只返回日期 2:只返回时间
  5. * @dateComplete[可选,默认:true] Boolean 日期位数不足是否添0补齐:true:补齐,false:不补齐
  6. * @timeComplete[可选,默认:true] Boolean 时间位数不足是否添0补齐:true:补齐,false:不补齐
  7. * @dateConnector[可选,默认:-] String 年月日连接符 例: - : /
  8. * @timeConnector[可选,默认::] String 时间连接符 例: - : /
  9. * @hour12[可选,默认:false] Boolean 是否返回12小时制时间 例: true:返回12小时制时间 false:返回24小时制时间
  10. * @return '2019-11-25 15:05:54' String 返回示例
  11. * **/
  12. format.dateTimeFliter = function(time, part = 0, dateComplete = true, timeComplete = true, dateConnector = '-',
  13. timeConnector = ':', hour12 = false) {
  14. let year = time.getFullYear()
  15. let month = time.getMonth() + 1
  16. let day = time.getDate()
  17. let hour = time.getHours()
  18. let minute = time.getMinutes()
  19. let second = time.getSeconds()
  20. let dateStr = ''
  21. let timeStr = ''
  22. //转换日期
  23. if (dateComplete) { //添0补齐
  24. if (month < 10) {
  25. month = '0' + month
  26. }
  27. if (day < 10) {
  28. day = '0' + day
  29. }
  30. }
  31. dateStr = year + dateConnector + month + dateConnector + day
  32. //转换时间
  33. //修改小时制
  34. if (hour12) {
  35. if (hour > 12) {
  36. hour = hour - 12
  37. if (timeComplete) {
  38. if (hour < 10) {
  39. hour = '下午 ' + '0' + hour
  40. } else {
  41. hour = '下午 ' + hour
  42. }
  43. }
  44. } else {
  45. if (timeComplete) {
  46. if (hour < 10) {
  47. hour = '上午 ' + '0' + hour
  48. } else {
  49. hour = '上午 ' + hour
  50. }
  51. }
  52. }
  53. }
  54. //判断分钟与秒
  55. if (timeComplete) { //添0补齐
  56. if (minute < 10) {
  57. minute = '0' + minute
  58. }
  59. if (second < 10) {
  60. second = '0' + second
  61. }
  62. }
  63. timeStr = hour + timeConnector + minute + timeConnector + second
  64. //合成输出值
  65. if (part == 0) {
  66. return dateStr + ' ' + timeStr
  67. } else if (part == 1) {
  68. return dateStr
  69. } else if (part == 2) {
  70. return timeStr
  71. }
  72. return '传参有误'
  73. }
  74. function formatInt(int) {
  75. return int < 10 ? `0${int}` : int
  76. }
  77. format.formatDuration = function(duration) {
  78. if (duration < 60) {
  79. return `00:00:${formatInt(duration)}`
  80. }
  81. if (duration < 60 * 60) {
  82. const min = parseInt(duration / 60)
  83. const sec = duration - min * 60
  84. return `00:${formatInt(min)}:${formatInt(sec)}`
  85. }
  86. const hour = parseInt(duration / (60 * 60))
  87. const remainder = duration - hour * (60 * 60)
  88. const min = parseInt(remainder / 60)
  89. const sec = remainder - min * 60
  90. return `${formatInt(hour)}:${formatInt(min)}:${formatInt(sec)}`
  91. }
  92. export default format