js獲取當(dāng)前日期昨天、今天、明天日期的不同方法總結(jié)
一、方法一
1. 獲取當(dāng)前日期
var today = new Date();
2. 獲取昨天的日期
var yesterday = this.getDay(-1)
3. 獲取今天的日期
var today = this.getDay(0)
5. 獲取明天的日期
var tomorrow = this.getDay(1)
6. 調(diào)用的方法示例代碼如下所示:
獲取當(dāng)前日期昨天、今天、明天的日期
methods: {
getDay(day) {
var today = new Date();
var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
today.setTime(targetday_milliseconds); //注意,這行是關(guān)鍵代碼
var tYear = today.getFullYear();
var tMonth = today.getMonth();
var tDate = today.getDate();
tMonth = this.doHandleMonth(tMonth + 1);
tDate = this.doHandleMonth(tDate);
return tYear + "-" + tMonth + "-" + tDate;
},
doHandleMonth(month) {
var m = month;
if (month.toString().length == 1) {
m = "0" + month;
}
return m;
},
},
二、方法二
1. 獲取當(dāng)前日期
var today = new Date();
2. 獲取昨天的日期
today .setTime(day1.getTime()-24*60*60*1000); var yesterday = today .getFullYear()+"-" + (today .getMonth()+1) + "-" + today .getDate();
3. 獲取今天的日期
today .setTime(today .getTime()); var day= today .getFullYear()+"-" + (today .getMonth()+1) + "-" + today .getDate();
4. 獲取明天的日期
today .setTime(today .getTime()+24*60*60*1000); var tomorrow= today .getFullYear()+"-" + (today .getMonth()+1) + "-" + today .getDate();
總結(jié):
知識小結(jié):
總結(jié):
- 獲取當(dāng)前日期并進行計算想要的日期
{
text: '本月',
onClick(picker) {
// 獲取當(dāng)前日期
const today = new Date();
// 獲取當(dāng)前月份的第一天
const start = new Date(today.getFullYear(), today.getMonth(), 1);
// 獲取當(dāng)前月份的最后一天
const end = new Date(today.getFullYear(), today.getMonth() + 1, 0);
picker.$emit('pick', [start, end]);
}
},
- 1、傳值調(diào)用此方法
created() {
console.log("昨天:", this.getDay(-1))
console.log("今天:", this.getDay(0))
console.log("明天:", this.getDay(1))
console.log("20年以后:", this.getDay(20 * 365))
}
- 獲取當(dāng)前時間, new Date()
- day為number,getDay(-1):昨天的日期;getDay(0):今天的日期;getDay(1):明天的日期;
附:js獲取當(dāng)前星期幾的方法
JavaScript中的Date對象提供了獲取當(dāng)前日期和時間的方法。其中,getDay()方法可以返回當(dāng)前星期,返回值為0-6,分別代表星期日到星期六。
以下是使用Date對象獲取當(dāng)前星期幾的示例代碼:
const weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const today = new Date();
const dayOfWeek = weekDays[today.getDay()];
console.log(`Today is ${dayOfWeek}`);
在上面的代碼中,我們首先定義了一個包含星期日到星期六的數(shù)組weekDays。然后,我們創(chuàng)建了一個Date對象,使用getDay()方法獲取當(dāng)前星幾,并使用數(shù)組weekDays獲取對應(yīng)的星期幾名稱。
到此這篇關(guān)于js獲取當(dāng)前日期昨天、今天、明天日期的不同方法的文章就介紹到這了,更多相關(guān)js獲取當(dāng)前日期昨天、今天、明天內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript駕馭網(wǎng)頁-獲取網(wǎng)頁元素
這篇文章主要介紹了JavaScript駕馭網(wǎng)頁-獲取網(wǎng)頁元素的相關(guān)資料,需要的朋友可以參考下2016-03-03
JavaScript動態(tài)創(chuàng)建form表單并提交的實現(xiàn)方法
這篇文章主要介紹了JavaScript動態(tài)創(chuàng)建form表單并提交的實現(xiàn)方法,涉及JavaScript動態(tài)創(chuàng)建頁面元素及模擬表單提交的技巧,需要的朋友可以參考下2015-12-12

