本文介绍了为什么在转换为日期对象时从JavaScript中减去1个月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在书中的解释阅读说:嗯,我的姨妈从其他人开始算起她的月份,所以我们减去1。

The explanation in the book I am reading says, "Well, my Aunt starts counting her months from 1 like everyone else, so we subtract 1.

这是输入字符串日期: 死亡27/04/2006:黑色Leclère

Here's the input string date: "died 27/04/2006: Black Leclère"

以下是代码:

function extractDate(paragraph) {
  function numberAt(start, length) {
    return Number(paragraph.slice(start, start + length));
  }
  return new Date(numberAt(11, 4), numberAt(8, 2) - 1,
                  numberAt(5, 2));
}

alert(extractDate("died 27-04-2006: Black Leclère"));

04 - 1是03.但这是输出日期对象: 2006年4月27日00:00:00

04 - 1 is 03. But here's the output date object: Thu Apr 27 2006 00:00:00.

会心我们想要的输出不能解释语言的异常行为和随后的-1的必要性。请解释。

Knowing what we want for the output doesn't explain the unusual behavior of the language and the subsequent necessity of the -1. Please, explain.

推荐答案

JavaScript日期对象表示的月份为0。也就是说,1月份表示为 0 ,2月份为 1 ,3月为 2

Months represented in JavaScript Date objects are 0-based. That is, January is represented as 0, February as 1, March as 2, etc.

有关为什么这种行为在多种语言中实现的一些有趣的答案,请参阅。

For some interesting answers as to why this behaviour is implemented across many languages, see Zero-based month numbering.

这篇关于为什么在转换为日期对象时从JavaScript中减去1个月?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:21