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.
1517769000
I'm getting that like this(This is a RN project)
var selectedDate = moment(this.state.date).unix();
Now I need to get only the year from above date in JS. I tried selectedDate.year() as well. But it's always getting 1970. Please help me to solve this.
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.
1517769000
I'm getting that like this(This is a RN project)
var selectedDate = moment(this.state.date).unix();
Now I need to get only the year from above date in JS. I tried selectedDate.year() as well. But it's always getting 1970. Please help me to solve this.
Share Improve this question edited Feb 22, 2018 at 18:26 apple_92 asked Feb 22, 2018 at 18:20 apple_92apple_92 2632 gold badges7 silver badges18 bronze badges 2- Given it’s a moment object you should just be able to do moment(selectedDate).year() and it will give you the year. Refer to member.js docs for formatting options. Updated accordingly. – SwankTheTank Commented Feb 22, 2018 at 18:24
- 1 See what is collected as "Related" on the right. A mere search could have worked too... – tevemadar Commented Feb 22, 2018 at 18:25
5 Answers
Reset to default 3This 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
Here you go..
new Date(selectedDate).getFullYear();
simply multiply the timestamp with 1000 -> ms.
date = new Date(1517769000 * 1000).getFullYear()
Unix timestamps do not include microseconds, whereas Javascript dates do.
new Date(selectedDate * 1000).getFullYear();
will yield the correct value when you feed it a Unix timestamp.
The other answers are correct if the timestamp came from JavaScript in the first place.
Unix time (<-that is a link, just not very visible)
number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 [...]
new Date() (<- also a link)
Date objects are based on a time value that is the number of milliseconds since 1 January 1970 UTC [...]
Multiply with 1000, then it will bee better:
console.log(new Date(1517769000*1000).getFullYear());
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745614151a4636128.html
评论列表(0条)