gpt4 book ai didi

javascript - 使用 getMonth() 获取不同的输出

转载 作者:行者123 更新时间:2023-11-30 20:13:59 25 4
gpt4 key购买 nike

我正在尝试使用此函数来验证用户是否有 18 年或更长时间,但在使用 getMonth() 时出现不稳定的行为。即如果我输入 1,ir 返回 0,但是如果我输入 2,它返回 2:

function validacion() {
var anio = parseInt($('#year').val()); //year
var mes = parseInt($('#month').val()); //month
var dia = parseInt($('#day').val()); //day
var convertirMes = mes-1;
var ObjFechaFicticia = new Date();
var setearAnioFicticio = ObjFechaFicticia.setFullYear(anio); //year user input
var setearMesFicticio = ObjFechaFicticia.setMonth(convertirMes); //month user input
var setearDiasFicticio = ObjFechaFicticia.setDate(dia); //day user input

var ObjFechaActual = new Date();
var anioActual = ObjFechaActual.getFullYear();
var mesActual = ObjFechaActual.getMonth()+1;
var diaActual = ObjFechaActual.getDate();

console.log("Fecha real: "+diaActual+'/'+mesActual+'/'+anioActual)
console.log("Fecha ficticia :"+ObjFechaFicticia.getDate()+"/"+ObjFechaFicticia.getMonth()+"/"+ObjFechaFicticia.getFullYear())

最佳答案

这是因为您更改日期对象的顺序......今天,2018 年 8 月 31 日

假设您想输入 2018 年 2 月 4 日

const outputDate = d => {
console.log(`${d.getFullYear()}, ${d.getMonth() + 1}, ${d.getDate()}`);
}
var d = new Date();
outputDate(d); // d is 2018, 8, 31
d.setFullYear(2001);
outputDate(d); // d is 2000, 8, 31
d.setMonth(1); // set february
outputDate(d); // d is 2000, 3, 3 // 3 is March!!
d.setDate(4);
outputDate(d); // d is 2000, 3, 4 // 3 is March!!
console.log(d+'');

现在,如果你改变日,然后是月,然后是年

const outputDate = d => {
console.log(`${d.getFullYear()}, ${d.getMonth() + 1}, ${d.getDate()}`);
}
var d = new Date();
outputDate(d);
d.setDate(4);
outputDate(d);
d.setMonth(1); // set february
outputDate(d);
d.setFullYear(2001);
outputDate(d);
console.log(d+'');

当然,你应该这样做

 var ObjFechaFicticia = new Date(anio, convertirMes, dia);

一切都会很甜蜜

关于javascript - 使用 getMonth() 获取不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com