繁体   English   中英

以 dd.mm.yyyy 格式获取母亲节日期

[英]Get motherday date in format dd.mm.yyyy

我试图通过 Javascript 获得母亲节日期(5 月的第一个星期日)。 但是我的代码的结果是 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());

这是执行此操作的正确方法,没有容易出错的计算或字符串连接,包括将其格式化为 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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM