简体   繁体   English

如何仅从Unix时间戳获取年份?

[英]How to get only the year from unix time stamp?

My project has a date picker and when user selects a date I'm getting it to unix time stamp and it look like following. 我的项目有一个日期选择器,当用户选择一个日期时,我会将其设置为unix时间戳,如下图所示。

1517769000

I'm getting that like this(This is a RN project) 我得到这样的(这是一个RN项目)

var selectedDate = moment(this.state.date).unix();

Now I need to get only the year from above date in JS. 现在,我只需要从JS中获取上述日期中的年份。 I tried selectedDate.year() as well. 我也尝试了selectedDate.year()。 But it's always getting 1970. Please help me to solve this. 但是它总是在1970年。请帮助我解决这个问题。

This should do the trick 这应该可以解决问题

 let date = new Date(1517769000 * 1000).getFullYear() console.log(date) 

EDIT 编辑

added multiplication by 1000 as Unix timestamp is in seconds and JavaScript Date is in msecs Unix时间戳以秒为单位,而JavaScript Date以毫秒为单位,则乘以1000

干得好..

new Date(selectedDate).getFullYear();

只需将时间戳乘以1000-> ms。

date = new Date(1517769000 * 1000).getFullYear()

Unix timestamps do not include microseconds, whereas Javascript dates do. Unix时间戳不包含微秒,而Javascript日期包含。

new Date(selectedDate * 1000).getFullYear();

will yield the correct value when you feed it a Unix timestamp. 当您将其输入Unix时间戳时,它将产生正确的值。

The other answers are correct if the timestamp came from JavaScript in the first place. 如果时间戳首先来自JavaScript,则其他答案是正确的。

Unix time (<-that is a link, just not very visible) Unix时间 (<-这是一个链接,只是不太明显)

number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 [...] 00:00:00以来的协调世界时(UTC)已经过去的秒数 ,周四,1970年1月1日[...]

new Date() (<- also a link) 新的Date() (<-也是一个链接)

Date objects are based on a time value that is the number of milliseconds since 1 January 1970 UTC [...] 日期对象基于时间值,该时间值是自1970年1月1日UTC [...]起的毫秒数。

Multiply with 1000, then it will become better: 乘以1000,它将变得更好:

 console.log(new Date(1517769000*1000).getFullYear()); 

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

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