我试着用Javascript获取母亲节的日期(五月的第一个星期天)。但是我的代码的结果是0.4.2021。错误在哪里,或者有一种更简单的方法来获取母亲节日期(dd.mm.yyyy) (德国时区)。
var currentYear = new Date().getFullYear()
var mayFirst = new Date(currentYear + '-05-01');
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek === 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date();
firstSunday.setDate(1 + (7 - dayOfWeek));
}
var mothersDay = new Date(firstSunday);
mothersDay.setDate(firstSunday.getUTCDate() + 7);
mothersDay = new Date(mothersDay);
console.log(mothersDay.getDay() + "." + mothersDay.getMonth() + "." + mothersDay.getFullYear());
发布于 2021-05-06 18:51:20
下面是执行此操作的正确方法,无需进行容易出错的计算或字符串连接,包括将其格式化为DD.MM.YYYY:
// Mother's Day is the second sunday in May
const d = new Date();
d.setMonth(4); // May
d.setDate(8); // May 8 is the earliest possible date
// while not a sunday, move to next day
while (d.getUTCDay()) d.setDate(d.getDate() + 1);
const result = new Intl.DateTimeFormat('de-DE', { day: "2-digit", month: "2-digit", year: "numeric"}).format(d);
document.body.innerHTML += result;
发布于 2021-05-06 18:43:18
getMonth()是基于0的,所以你需要加1。此外,您还希望使用getDate()而不是getDay()来获取日期的日期值。
我假设你想得到5月的第二个星期天,因为你的代码中的下面这行代码加上了7天。如果你想要第一个星期天,你也应该删除这一行。
mothersDay.setDate(firstSunday.getUTCDate() + 7);
var currentYear = new Date().getFullYear()
var mayFirst = new Date(currentYear + '-05-01');
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek === 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date();
firstSunday.setDate(1 + (7 - dayOfWeek));
}
var mothersDay = new Date(firstSunday);
mothersDay.setDate(firstSunday.getUTCDate() + 7);
mothersDay = new Date(mothersDay);
console.log(mothersDay.getDate() + "." + (mothersDay.getMonth() + 1) + "." + mothersDay.getFullYear());
https://stackoverflow.com/questions/67416414
复制相似问题