util.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const formatTime = (date, fmt) => {
  2. if (!date) {
  3. return fmt;
  4. }
  5. var o = {
  6. "M+": date.getMonth() + 1, //月份
  7. "d+": date.getDate(), //日
  8. "H+": date.getHours(), //小时
  9. "m+": date.getMinutes(), //分
  10. "s+": date.getSeconds(), //秒
  11. "q+": Math.floor((date.getMonth() + 3) / 3), //季度
  12. "S": date.getMilliseconds() //毫秒
  13. };
  14. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  15. for (var k in o)
  16. if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  17. return fmt;
  18. }
  19. const formatNumber = n => {
  20. n = n.toString()
  21. return n[1] ? n : '0' + n
  22. }
  23. //将年月日数组转成时间戳
  24. const argusToTimestamp = arr => {
  25. var lenth = arr.length;
  26. if (lenth < 3) {
  27. for (var i = 0; i < 3 - lenth; i++) {
  28. arr.push("01")
  29. }
  30. }
  31. return Date.parse(new Date(arr.join("/")))
  32. }
  33. // 时间戳转成年月
  34. function formateym(dates, split = ".") {
  35. var date = new Date(+dates)
  36. var year = date.getFullYear()
  37. var month = date.getMonth() + 1
  38. var day = date.getDate()
  39. return date.getFullYear() + split + formatNumber(date.getMonth() + 1)
  40. }
  41. // 时间转成年月
  42. function formateYM(date, status = true) {
  43. const _date = date.replace(/-/g, '/')
  44. var time = new Date(date)
  45. var year = time.getFullYear()
  46. var month = time.getMonth() + 1
  47. var day = time.getDate()
  48. if (status) {
  49. return `${year}年${month}月`
  50. } else {
  51. return `${year}年${month}月${day}`
  52. }
  53. }
  54. // 时间转成年月
  55. function formatetime(date, str, status = true) {
  56. const _date = date.replace ? date.replace(/-/g, '/') : date;
  57. var time = new Date(_date)
  58. var year = time.getFullYear()
  59. var month = time.getMonth() + 1
  60. var day = time.getDate()
  61. if (status) {
  62. return `${year}${str}${month}`
  63. } else {
  64. return `${year}${str}${month}${str}${day}`
  65. }
  66. }
  67. function testPhone(data) {
  68. const phone_zz = /^1[3-9]\d{9}$/;
  69. return phone_zz.test(data)
  70. }
  71. module.exports = {
  72. formatTime: formatTime,
  73. formatNumber,
  74. formateym,
  75. argusToTimestamp,
  76. formateYM,
  77. formatetime,
  78. testPhone
  79. }