如何使用 JavaScript 计算三个月前的日期?


要使用 JavaScript 计算三个月前的日期,我们首先需要创建一个新的日期对象,它将表示当前日期。然后,我们将使用 setMonth() 方法从当前月份减去 3。最后,我们将使用 toString 方法将此新的日期对象转换回字符串,以显示三个月前的日期。

基本上,我们将编写一个动态的 JavaScript 函数,它可以接收一个数字作为输入,并返回从今天的日期算起之前该数字月份的日期。

例如 -

calculatePriorDate(4);

假设今天的日期是 2023 年 1 月 19 日(格式为 DD/MM/YYYY),则此函数应返回 2022 年 9 月 19 日。

方法

  • 这是一个简单的功能,可以使用原生的 JS Date 对象实现。

  • 我们将使用 JS Date 的 getMonthsetMonth 方法分别获取和设置新的月份。

  • 负责执行此操作的函数将如下所示 -

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(); };

此函数将简单地接收月份间隔,并在减去所需的月份数后返回先前的日期字符串。

示例

此功能的完整工作代码将是 -

Open Compiler
<!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>

更新于: 2023 年 2 月 16 日

2K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告