欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 对当前日期进行按年、按月、按日的取值

对当前日期进行按年、按月、按日的取值

2025/2/23 13:24:02 来源:https://blog.csdn.net/snow_living/article/details/144115219  浏览:    关键词:对当前日期进行按年、按月、按日的取值

 对当前日期进行按年、按月、按日的取值。

其规则为:

按年 为当前日期到来年同一日期的前一天(2024-12-01到2025-11-30)。

按月 为当前日期到下个月的同一日期的前一天 (2024-12-01 到 2024-12-31)。

按日  为当前日期到下一日(2024-12-01 到 2024-12-02)

实验多种方式 ,要么引入组件 要么拆分重组 很麻烦,最后试了个方法觉得挺简便的, 记录下来。

组件用的是vue3的 DatePicker 日期选择器 

      <div style="display: flex; width: 100%; justify-content: space-between"><el-date-pickerv-model="form.StartTime" format="YYYY-MM-DD"value-format="YYYY-MM-DD"type="date"placeholder="开始日期"@change="changeEnterprise"/><div>—</div><el-date-pickerv-model="form.EndTime"format="YYYY-MM-DD"value-format="YYYY-MM-DD"type="date"placeholder="结束日期"disabled/></div>

组件改写选择开始时间,结束时间自动计算。 

   <el-select v-model="form.report" placeholder="请选择时间类型" @change="changeType"><el-option v-for="dict in bus_report_type" :key="dict.value" :label="dict.label" :value="dict.value" />
// 此段代码是字典表取值 转译成假数据<el-option key="0" label="按年" value="0"><el-option key="1" label="按月" value="1"><el-option key="2" label="按日" value="2"></el-select>

 选完时间类型后,显示结束时间。

//根据类型查周期
const changeEnterprise = () => {if (form.value.Type) {const dataTime = new Date(form.value.StartTime);if (form.value.Type == 0) {// 增加一年dataTime.setFullYear(dataTime.getFullYear() + 1);// 减去一天dataTime.setDate(dataTime.getDate() - 1);}if (form.value.Type == 1) {// 增加一个月dataTime.setMonth(dataTime.getMonth() + 1);// 减去一天dataTime.setDate(dataTime.getDate() - 1);}if (form.value.Type == 2) {// 增加一天dataTime.setDate(dataTime.getDate() + 1);}// 格式化日期为 YYYY-MM-DD 字符串const year = dataTime.getFullYear();const month = String(dataTime.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以需要+1,并且补零const day = String(dataTime.getDate()).padStart(2, '0'); // 日期可能也需要补零form.value.EndTime = `${year}-${month}-${day}`;console.log('startDate', dataTime, form.value.EndTime);} else {form.value.Type = null;}
};

附加一个设置 dateTime 的默认值为当前月的第一天到最后一天 

// 获取当前日期
const currentDate = new Date();// 获取当前月的第一天
const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth());// 获取当前月的最后一天
const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);// 将日期格式化为 YYYY-MM-DD
const formatDate = (date) => {const year = date.getFullYear();const month = String(date.getMonth() + 1).padStart(2, '0');const day = String(date.getDate()).padStart(2, '0');return `${year}-${month}-${day}`;
};// 设置 dateTime 的默认值为当前月的第一天到最后一天
const dateTime = ref([formatDate(firstDay), formatDate(lastDay)]);

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词