| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- // 获取当前年月的月初第一天和月末最后一天
- export function getMonthRange() {
- const now = new Date();
- const year = now.getFullYear();
- const month = now.getMonth();
-
- // 获取当前月份的第一天
- const firstDay = new Date(year, month, 1);
-
- // 获取当前月份的最后一天
- const lastDay = new Date(year, month + 1, 0);
-
- // 格式化日期为 YYYY-MM-DD
- const formatDate = (date) => {
- const y = date.getFullYear();
- const m = String(date.getMonth() + 1).padStart(2, '0');
- const d = String(date.getDate()).padStart(2, '0');
- return `${y}-${m}-${d}`;
- };
-
- return {
- firstDay: formatDate(firstDay),
- lastDay: formatDate(lastDay)
- };
- }
-
- export function getMonth(dateStr) {
- if (!dateStr || !/^\d{4}-\d{2}$/.test(dateStr)) {
- throw new Error('请输入正确的 YYYY-MM 格式日期');
- }
-
- const [year, month] = dateStr.split('-').map(Number);
- const firstDay = new Date(year, month - 1, 1); // 月份从 0 开始,所以需要减 1
- const lastDay = new Date(year, month, 0); // 下个月的第 0 天即为当前月的最后一天
-
- // 格式化日期为 YYYY-MM-DD
- const formatDate = (date) => {
- const y = date.getFullYear();
- const m = String(date.getMonth() + 1).padStart(2, '0');
- const d = String(date.getDate()).padStart(2, '0');
- return `${y}-${m}-${d}`;
- };
-
- return {
- firstDay: formatDate(firstDay),
- lastDay: formatDate(lastDay)
- };
- }
- // 获取天数
- export function getDays(year, month) {
- // 参数处理
- const monthNum = typeof month === 'string' ? parseInt(month) : month;
- if (monthNum < 1 || monthNum > 12) {
- throw new Error('月份必须在1-12之间');
- }
-
- // 创建日期对象
- const date = new Date(year, monthNum - 1, 1);
- if (isNaN(date.getTime())) {
- throw new Error('无效的年份或月份');
- }
-
- // 获取当月最后一天
- const lastDay = new Date(year, monthNum, 0);
- const daysInMonth = lastDay.getDate();
-
- // 生成格式化后的天数数组(添加"日"后缀)
- const daysArray = Array.from({length: daysInMonth}, (_, i) => ({
- name: `${i + 1}日`, // 格式如:"1日"、"2日"
- id: i // id从0开始
- }));
-
- // 格式化日期
- const formatDate = (date) => {
- const y = date.getFullYear();
- const m = String(date.getMonth() + 1).padStart(2, '0');
- const d = String(date.getDate()).padStart(2, '0');
- return `${y}-${m}-${d}`;
- };
-
- return {
- daysArray, // 格式: [{name:"1日",id:0}, {name:"2日",id:1}, ...]
- daysInMonth, // 当月总天数
- firstDay: formatDate(new Date(year, monthNum - 1, 1)),
- lastDay: formatDate(lastDay),
- year,
- month: monthNum
- };
- }
|