问题描述
我正试图从日期中拉出一年,但是由于某种原因,它会在一年的第一天返回上一年。
I'm trying to pull just the year out of a date, but for some reason on the first day of the year its returning the year previous.
new Date('2012-01-01').getFullYear()
将返回'2011'和
new Date('2012-01-02').getFullYear()
将返回 2012
任何关于我做错了什么?
Any good ideas on what I'm doing wrong? or a fix for this would be helpful.
推荐答案
new Date('2012-01-01' )
会假设其采用UTC格式进行解析。创建的 Date
对象包含您的时区,因此在打印出 getYear()
的结果时会考虑到该时区。如果您参加了格林尼治标准时间(GMT)考试,则意味着您将回到上一年。您可以通过调用 Date.prototype.getUTCFullYear()
来忽略时区,仅处理UTC。
new Date('2012-01-01')
will parse the date assuming it's in UTC. The created Date
object incorporates your timezone, so it will take that into account when printing out the result of getYear()
. If you're in GMT-anything, that means you're going back to the previous year. You can ignore timezones and deal with just UTC by calling Date.prototype.getUTCFullYear()
.
这篇关于getFullYear在一年的第一天前一年返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!