如何在 JavaScript 中检索用户输入的月份的最后一天?
我有一个带有 2 个日期选择器的表单。目前,表单日期设置为 MM/YYYY(这就是我在表单中需要的方式)但是,对于日期验证,我需要日期格式为 MM/DD/YYYY。第一个日期只需设置为 MM/01/YYYY,第二个日期需要设置为 MM/lastDayOfMonth/YYYY。 以下是我到目前为止所做的事情。它返回该月的最后一天,但附带时间戳和日期。
var monthYear2 = $("#date2").val();
var month = monthYear2.slice(0,2);
var year = monthYear2.slice(3,7);
var lastDay = new Date(year, month + 1, 0);
var date2 = monthYear2.slice(0, 3) + lastDay + "/" + monthYear2.slice(3, 7)
我需要 date2 的最终变量采用 MM/lastDayOfMonth/YYYY 格式
最佳答案
我不明白您为什么要使用 month + 1
创建一个 Date
对象。如果是用户发送的当前月份,则只需使用月份
。
const userInput = '02/2019',
splitted = userInput.split('/'),
month = splitted[0],
year = splitted[1],
firstDayDate = `${month}/01/${year}`,
lastDayDate = `${month}/${new Date(year, month, 0).getDate()}/${year}`;
console.log(firstDayDate, lastDayDate);
关于javascript - 如何根据用户输入检索并设置该月的最后一天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55801519/