To explore this we're going to create a new playground file, over inside of Atom we're going to make a playground folder to store this file, and inside of the playground folder we can make a new file calling it time.js. In here it will play around with time, and we'll take what we learn here into the frontend of the application in the next section.
We are no strangers to timestamps, we know they're nothing more than just integers whether positive or negative, something like 781 is a perfectly valid timestamp, so is something like minus a couple of billion or whatever any number happens to be, all valid, even 0 is a perfectly valid timestamp. Now all of these numbers, they're all relative to a certain moment in history referred to as the Unix epoch, which is January 1, 1970 at midnight 0 hours 0 minutes and 0 seconds am. This is stored in UTC which means it's timezone independent:
// Jan 1st 1970 00:00:00 am
0
Now my time stamp 0 actually represents this moment in history perfectly, and positive numbers like 1000 head into the future, while negative numbers like -1000 head into the past. -1000 as a timestamp would represent December 31, 1969 at 11:59 and 59 seconds, we've gone one second into the past from January 1, 1970.
Now these timestamps inside of JavaScript, they're stored in milliseconds since the Unix epoch inside of regular Unix timestamps, they're actually stored in seconds. Since we are using JavaScript in this course, we will always be using milliseconds as our timestamp values, which means at a timestamp like this, 1000, represents one second into January 1st, since there's 1000 milliseconds in a second.
A value like 10000 would be ten seconds into this day and so on and so forth. Now the problem for us was never getting the timestamp, getting the timestamp was really easy, all we had to do was call new Date calling its getTime method. Things are going to get a lot harder though and we want to format a human-readable value like the one we have earlier.
We're going to want to print something to the screen inside of our web app that's not just the timestamp, we're going to want to print something like maybe five minutes ago, letting a user know the message was sent five minutes ago, or maybe you want to print the actual date with the month, day, hour, minute and A.M or P.M value. Regardless of what you want to print we are going to need to talk a bit about formatting, and this is where the default Date object falls short.
Yes there are methods that allow you to get the specific values out of a date, like the year, the month, or the day of month, but they are very limited and it is a huge burden to customize.