date_util.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. export function dateFormat(date, fmt) {
  2. let ret;
  3. const opt = {
  4. "Y+": date.getFullYear().toString(), // 年
  5. "m+": (date.getMonth() + 1).toString(), // 月
  6. "d+": date.getDate().toString(), // 日
  7. "H+": date.getHours().toString(), // 时
  8. "M+": date.getMinutes().toString(), // 分
  9. "S+": date.getSeconds().toString(), // 秒
  10. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  11. };
  12. for (let k in opt) {
  13. ret = new RegExp("(" + k + ")").exec(fmt);
  14. if (ret) {
  15. fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"));
  16. }
  17. }
  18. return fmt;
  19. }
  20. export function formatDateToYYYYMMDD(dateString) {
  21. // 创建一个 Date 对象
  22. const date = new Date(dateString);
  23. // 获取年、月、日部分
  24. const year = date.getFullYear();
  25. const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始,所以要加1,并且用padStart补0
  26. const day = String(date.getDate()).padStart(2, "0"); // 用padStart补0
  27. // 拼接成 YYYY.MM.DD 格式
  28. return `${year}.${month}.${day}`;
  29. }
  30. export function formatDate(dateStr) {
  31. // 创建一个 Date 对象
  32. const date = new Date(dateStr);
  33. // 提取年、月、日、小时、分钟和秒
  34. const year = date.getFullYear();
  35. const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始,需要加1
  36. const day = String(date.getDate()).padStart(2, "0");
  37. const hours = String(date.getHours()).padStart(2, "0");
  38. const minutes = String(date.getMinutes()).padStart(2, "0");
  39. const seconds = String(date.getSeconds()).padStart(2, "0");
  40. // 格式化日期字符串
  41. const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  42. return formattedDate;
  43. }