如何使用 JavaScript 計算三個月前的日期?
要使用 JavaScript 計算三個月前的日期,我們首先需要建立一個新的日期物件,它將表示當前日期。然後,我們將使用 setMonth() 方法從當前月份減去 3。最後,我們將使用 toString 方法將此新的日期物件轉換回字串,以顯示三個月前的日期。
基本上,我們將編寫一個動態的 JavaScript 函式,它可以接收一個數字作為輸入,並返回從今天的日期算起之前該數字月份的日期。
例如 -
calculatePriorDate(4);
假設今天的日期是 2023 年 1 月 19 日(格式為 DD/MM/YYYY),則此函式應返回 2022 年 9 月 19 日。
方法
這是一個簡單的功能,可以使用原生的 JS Date 物件實現。
我們將使用 JS Date 的 getMonth 和 setMonth 方法分別獲取和設定新的月份。
負責執行此操作的函式將如下所示 -
const calculatePriorDate = (priorMonths = 1) => {
const date = new Date();
// accessing current month of the date
const currentMonth = date.getMonth();
// subtracting required number of months
date.setMonth(currentMonth - priorMonths);
return date.toLocaleDateString();
};
此函式將簡單地接收月份間隔,並在減去所需的月份數後返回先前的日期字串。
示例
此功能的完整工作程式碼將是 -
<!DOCTYPE html>
<html>
<head>
<title>Prior Date</title>
<style>
#space {
color: black;
}
</style>
</head>
<body>
<input placeholder = 'Input Gap...' id = 'gap' />
<button onclick = 'renderGap()'>Calculate</button>
<p id = 'space'></p>
<script>
const calculatePriorDate = (priorMonths = 1) => {
const date = new Date();
// accessing current month of the date
const currentMonth = date.getMonth();
// subtracting required number of months
date.setMonth(currentMonth - priorMonths);
return date.toLocaleDateString();
};
const renderGap = () => {
const space = document.getElementById('space');
const gapInput = document.getElementById('gap');
const gap = parseInt(gapInput.value) || 1;
const newDate = calculatePriorDate(gap);
space.innerText = newDate;
}
</script>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP