为什么在转换为日期对象时从JavaScript中减去1个月? [英] Why subtract 1 from months in JavaScript when converting to a date object?

查看:441
本文介绍了为什么在转换为日期对象时从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.


基于数组和1个月的值确实带来了一个问题。要获取月份的月份名称,您必须从月份数组中获取项目8,有些开发人员会在获得名称之前减少月份号码感到满意。更愿意把这个月改成零,因为人们只是想知道这个名字,而不是数字。这是个人看法。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆