util.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const formatTime = date => {
  2. const year = date.getFullYear();
  3. const month = date.getMonth() + 1;
  4. const day = date.getDate();
  5. const hour = date.getHours();
  6. const minute = date.getMinutes();
  7. const second = date.getSeconds();
  8. return `${[year, month, day].map(formatNumber).join("/")} ${[
  9. hour,
  10. minute,
  11. second
  12. ]
  13. .map(formatNumber)
  14. .join(":")}`;
  15. };
  16. const formatNumber = n => {
  17. n = n.toString();
  18. return n[1] ? n : `0${n}`;
  19. };
  20. //获得对应时间格式
  21. const formatTime2 = (time, type) => {
  22. var date = new Date(time);
  23. var format = type || "YYYY-MM-DD HH:NN:SS";
  24. const year = date.getFullYear();
  25. const month =
  26. date.getMonth() + 1 < 10
  27. ? "0" + (date.getMonth() + 1)
  28. : date.getMonth() + 1;
  29. const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  30. const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  31. const minute =
  32. date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  33. const second =
  34. date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  35. format.indexOf("YYYY") > -1 ? (format = format.replace("YYYY", year)) : "";
  36. format.indexOf("MM") > -1 ? (format = format.replace("MM", month)) : "";
  37. format.indexOf("DD") > -1 ? (format = format.replace("DD", day)) : "";
  38. format.indexOf("HH") > -1 ? (format = format.replace("HH", hour)) : "";
  39. format.indexOf("NN") > -1 ? (format = format.replace("NN", minute)) : "";
  40. format.indexOf("SS") > -1 ? (format = format.replace("SS", second)) : "";
  41. return format;
  42. };
  43. module.exports = {
  44. formatTime,
  45. formatTime2
  46. };