apple_92
apple_92

Reputation: 263

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.

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.

Upvotes: 2

Views: 4730

Answers (5)

Evya
Evya

Reputation: 2375

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

Upvotes: 3

tevemadar
tevemadar

Reputation: 13195

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 become better:

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

Upvotes: 0

Raith
Raith

Reputation: 528

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.

Upvotes: 0

Simon Schweizer
Simon Schweizer

Reputation: 31

simply multiply the timestamp with 1000 -> ms.

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

Upvotes: 0

Randy Casburn
Randy Casburn

Reputation: 14165

Here you go..

new Date(selectedDate).getFullYear();

Upvotes: 0

Related Questions