【问题标题】:Difficult function isLeapYear [closed]困难的功能是LeapYear [关闭]
【发布时间】:2021-04-10 14:00:53
【问题描述】:

我应该写一个函数 isLeapYear.t 应该接受一个毫秒数或日期字符串作为参数。此函数检查传递的参数是否为闰年。如果是闰年,函数应该返回一个字符串——‘“年”是闰年’,如果不是,应该返回字符串——‘“年”不是闰年’。我应该使用 Date 对象。我知道这不是我想要的工作

if (year % 400 == 0)
  leap = true;
else if (year % 100 == 0)
  leap = false;
else if (year % 4 == 0)
  leap = true;
else
  leap = false;

For Example isLeapYear('2020-01-01 00:00:00'); // =>  ‘2020 is a leap year’
isLeapYear('2020-01-01 00:00:00777'); // =>  ‘Invalid Date’
isLeapYear('2021-01-15 13:00:00');  // =>  ‘2021 is not a leap year’
isLeapYear('2200-01-15 13:00:00'); // =>  ‘2200 is not a leap year’
isLeapYear(1213131313135465656654564646542132132131); // =>  ‘Invalid Date’
isLeapYear(1213131313); ); // => ‘1970 is not a leap year’

【问题讨论】:

标签: javascript arrays function date numbers


【解决方案1】:

我假设你想要 JS,尽管示例在上帝知道什么

const isLeapYearHelper = (year) => (year % 400 == 0 ? true : year % 100 == 0 ? false : year % 4 == 0 ? true : false)

const isLeapYear = (str) => {
const date = new Date(str)
const isValid = !isNaN(date.getTime())
return isValid ? isLeapYearHelper(date.getFullYear()) ? `${date.getFullYear()} is a leap year` : `${date.getFullYear()} is a not leap year` : 'Invalid Date'
}

console.log(isLeapYear('2020-01-01 00:00:00777'))
console.log(isLeapYear('2021-01-15 13:00:00'))
console.log(isLeapYear('2200-01-15 13:00:00'))
console.log(isLeapYear('2020-01-15 13:00:00'))
console.log(isLeapYear(1213131313135465656654564646542132132131))
console.log(isLeapYear(1213131313))

【讨论】:

  • 请解释一下
  • "在第 5 版规范出来之前,Date.parse 方法完全依赖于实现...... 8601 (另见什么是 JavaScript 中的有效日期时间字符串?)。但除此之外,没有要求 Date.parse / new Date(string) 应该接受什么,除了他们必须接受任何 Date#toString 输出...... "
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多