云链智安app
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

date.js 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // 获取当前年月的月初第一天和月末最后一天
  2. export function getMonthRange() {
  3. const now = new Date();
  4. const year = now.getFullYear();
  5. const month = now.getMonth();
  6. // 获取当前月份的第一天
  7. const firstDay = new Date(year, month, 1);
  8. // 获取当前月份的最后一天
  9. const lastDay = new Date(year, month + 1, 0);
  10. // 格式化日期为 YYYY-MM-DD
  11. const formatDate = (date) => {
  12. const y = date.getFullYear();
  13. const m = String(date.getMonth() + 1).padStart(2, '0');
  14. const d = String(date.getDate()).padStart(2, '0');
  15. return `${y}-${m}-${d}`;
  16. };
  17. return {
  18. firstDay: formatDate(firstDay),
  19. lastDay: formatDate(lastDay)
  20. };
  21. }
  22. export function getMonth(dateStr) {
  23. if (!dateStr || !/^\d{4}-\d{2}$/.test(dateStr)) {
  24. throw new Error('请输入正确的 YYYY-MM 格式日期');
  25. }
  26. const [year, month] = dateStr.split('-').map(Number);
  27. const firstDay = new Date(year, month - 1, 1); // 月份从 0 开始,所以需要减 1
  28. const lastDay = new Date(year, month, 0); // 下个月的第 0 天即为当前月的最后一天
  29. // 格式化日期为 YYYY-MM-DD
  30. const formatDate = (date) => {
  31. const y = date.getFullYear();
  32. const m = String(date.getMonth() + 1).padStart(2, '0');
  33. const d = String(date.getDate()).padStart(2, '0');
  34. return `${y}-${m}-${d}`;
  35. };
  36. return {
  37. firstDay: formatDate(firstDay),
  38. lastDay: formatDate(lastDay)
  39. };
  40. }
  41. // 获取天数
  42. export function getDays(year, month) {
  43. // 参数处理
  44. const monthNum = typeof month === 'string' ? parseInt(month) : month;
  45. if (monthNum < 1 || monthNum > 12) {
  46. throw new Error('月份必须在1-12之间');
  47. }
  48. // 创建日期对象
  49. const date = new Date(year, monthNum - 1, 1);
  50. if (isNaN(date.getTime())) {
  51. throw new Error('无效的年份或月份');
  52. }
  53. // 获取当月最后一天
  54. const lastDay = new Date(year, monthNum, 0);
  55. const daysInMonth = lastDay.getDate();
  56. // 生成格式化后的天数数组(添加"日"后缀)
  57. const daysArray = Array.from({length: daysInMonth}, (_, i) => ({
  58. name: `${i + 1}日`, // 格式如:"1日"、"2日"
  59. id: i // id从0开始
  60. }));
  61. // 格式化日期
  62. const formatDate = (date) => {
  63. const y = date.getFullYear();
  64. const m = String(date.getMonth() + 1).padStart(2, '0');
  65. const d = String(date.getDate()).padStart(2, '0');
  66. return `${y}-${m}-${d}`;
  67. };
  68. return {
  69. daysArray, // 格式: [{name:"1日",id:0}, {name:"2日",id:1}, ...]
  70. daysInMonth, // 当月总天数
  71. firstDay: formatDate(new Date(year, monthNum - 1, 1)),
  72. lastDay: formatDate(lastDay),
  73. year,
  74. month: monthNum
  75. };
  76. }