I’m working with an API that gives me timestamps like this: 1551268800 - so milliseconds since 1970, like getTime().
That translates to 12pm GMT time 27 Feb 2019. I’d like to represent it to the user as “Wednesday 12pm”, but searching how to do this doesn’t turn much up. Things I’ve tried so far:
var d = 1551268800;
var n = d.getDay();
console.log(n);
and
var n = getDay(1551646800);
console.log(n);
and:
new Date(1551646800)
I feel like the above is closest - it returns Mon Jan 19 1970 00:00:46 GMT+0100 (Greenwich Mean Time) {} in my console. It gets me close enough to the date format I want to start working on it - only problem is that it’s the wrong date!
Actually the timestamp you’re getting is in seconds, while Javascript expects milliseconds. So, multiply by 1000:
new Date(1551268800 * 1000);
For me this outputs (in the console): Wed Feb 27 2019 13:00:00 GMT+0100 (Central European Standard Time) {} - which is 1 hour ahead of GMT, so indeed GMT would be 12:00
So date.getMonth() returns 0 for January. 1 for February, etc …
Really thew me off the first time I used it, especially since days and years are not 0-based (well, year probably is, since the year 0 actually existed …)
Yes, use an array for the months too. Like the day of the week, months are an index value [0, 1, 2] and not a cardinal (1, 2, 3) or ordinal (1st, 2nd, 3rd) value.
Don’t worry, it didn’t look easy! And I’m working in React (which I’m new to), so taking your working code and shoving it in constructors, props and states etc is already enough of a maze to navigate.
Here’s a big long video (but with captions!) telling you to try as hard as possibly to not write any of this yourself unless it’s as a fun exercise
Also there’s this idea that Unix epoch slowly gets out of sync with UTC (your human date names), but that problem may be out of scope for whatever temporary thing you’re doing.
This has made my heart sink a bit. I’m doing this as a learning exercise around React, but I also wanted to make something useful. I’ve just realised timezones are going to be an issue! I’ll see what open source stuff is about.