简体   繁体   English

给定选定的年份,我需要在 JavaScript 中计算该年的第一天和最后一天

[英]Given a selected year, I need to calculate the first day and the last day of that year in JavaScript

Given a selected year, for example: "2020".给定选定的年份,例如:“2020”。 I need to calculate with JavaScript the first and the last day of the selected year in format: "2020-01-01" and "2020-12-31"我需要用 JavaScript 计算所选年份的第一天和最后一天的格式:“2020-01-01”和“2020-12-31”

Can someone help me with this?有人可以帮我弄这个吗? It will be possible doing it with Moment.js?使用 Moment.js 可以做到吗? Thanks in advance.提前致谢。

You can achieve it in this simple way您可以通过这种简单的方式实现它

 var formatDate = function(year, month, day) { if (month < 10) month = '0' + month; if (day < 10) day = '0' + day; return [year, month, day].join('-'); } var printDate = function(year){ console.log("Frist day: " + formatDate(year, 1, 1)); console.log("Last day: " + formatDate(year, 12, 31)); } printDate(2020);

I think the easiest and fastest approach is to not "calculate" anything.我认为最简单和最快的方法是不“计算”任何东西。 You don't need to.你不需要。

function firstOfYear(year) {
  return `${year}-01-01`;
}

function lastOfYear(year) {
  return `${year}-12-31`;
}

const start = firstOfYear(2020); // 2020-01-01
const end = lastOfYear(2020); // 2020-12-31

You might not even need the functions, depending on your use case.根据您的用例,您甚至可能不需要这些功能。

These functions aren't especially reusable, so if you have other dates you'd like to format then some of the other answers provided will be more flexible.这些函数不是特别可重用,因此如果您有其他日期想要格式化,那么提供的其他一些答案将更加灵活。 But if all you need to do is get the first and last of the year, then I recommend you keep it simple.但是,如果您需要做的只是获得一年中的第一天和最后一天,那么我建议您保持简单。

 CalculateDates = function(year){ console.log('first day: ' + new Date(year, 0, 1, 4).toJSON().split('T')[0]); console.log('last day: ' + new Date(year, 12, 0, 4).toJSON().split('T')[0]); } CalculateDates(2019)

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

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