①封装js方法文件,我一般存放在utils文件夹下面。
//封装的js文件名叫currentDate.js
const getDate = {
//对日期进行简单的增加和格式化操作,用于获取指定日期的后一天日期,并以特定格式返回。
getIntroDuctionDay(dateTime) {
let date = new Date(dateTime);
date.setDate(date.getDate() + 1);//将 date 对象的日期增加一天,表示取传入日期的后一天日期
let month = date.getMonth() + 1;
let strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
let currentdate = date.getFullYear() + "-" + month + "-" + strDate;
return currentdate;
},
//取当天日期,并以特定格式返回。
getTodayOnly() {
let date = new Date();
let month = date.getMonth() + 1;
let strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
//根据自己需求修改返回格式就行
let currentdate = date.getFullYear() + "-" + month + "-" + strDate;
return currentdate;
},
//获取传入日期的七天前日期 time是年月日没有时分秒哦~
frontSevenDays(time){
let now = new Date(time);
return formatDateTime(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7))
}
//获取具体时间 星期
getDetailedDate() {
var date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (day >= 0 && day <= 9) {
day = "0" + day;
}
let week = new Array(
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六"
)[date.getDay()];
let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
let minute =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
let second =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return `${year}年${month}月${day}日 ${week} ${hour}:${minute}:${second}`;
},
}
②在页面当中使用改方法,如下:
<script setup>
import { onMounted, reactive } from 'vue'
//注意 引入这个文件的名字需和你文件导出的名字一致getDate,否则会报错
import getDate from '@/utils/currentDate.js'
const appointMentDate = '2024-06-19 00:00:00'
onMounted(()=>{
//获取传入日期的后一天数据
const temp = getDate.getIntroDuctionDay(appointMentDate);
console.log('temp',temp);//会得到你传入日期的后一天日期数据 2024-06-20 00:00:00
//获取当天日期数据
const tempDay = getDate.getTodayOnly();
console.log('tempDay',tempday);// 2024-06-20 18:26:03
//获取七天前数据
const frontDay = getDate.frontSevenDays();
console.log('frontDay',frontDay);// 2024-06-12
//获取当天具体时间星期
const tempDateTime = getDate.getDetailedDate();
console.log('tempDateTime',tempDateTime);// 2024年06月19日 星期三 14:52:11
});
<script>
标签:00,vue,const,日期,&&,date,封装,getDate
From: https://blog.csdn.net/weixin_61001537/article/details/139801942