1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Convert Seconds To Date Object as a JavaScript TIL

This commit is contained in:
jbranchaud
2024-04-19 14:38:40 -05:00
parent 9684c6a6db
commit 505220d9de
2 changed files with 34 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1410 TILs and counting..._
_1411 TILs and counting..._
---
@@ -437,6 +437,7 @@ _1410 TILs and counting..._
- [Computed Property Names In ES6](javascript/computed-property-names-in-es6.md)
- [Conditionally Include Pairs In An Object](javascript/conditionally-include-pairs-in-an-object.md)
- [Configure Jest To Run A Test Setup File](javascript/configure-jest-to-run-a-test-setup-file.md)
- [Convert Seconds To Date Object](javascript/convert-seconds-to-date-object.md)
- [Create A Cancelable Promise With PCancelable](javascript/create-a-cancelable-promise-with-pcancelable.md)
- [Create An Array Containing 1 To N](javascript/create-an-array-containing-1-to-n.md)
- [Create An Object With No Properties](javascript/create-an-object-with-no-properties.md)

View File

@@ -0,0 +1,32 @@
# Convert Seconds To Date Object
Let's say you have an integer that represents the number of seconds since the
unix epoch. This is a reasonably common way for systems to represent a date.
For example, `1713350171` is an _Expiration Date_ I just got from an API.
But how do we know what date that actually represents and how can we get a
JavaScript `Date` object from that value?
The `new Date()` constructor can produce a date object given an integer. That
integer is not supposed to be seconds since the unix epoch though. See what we
get here:
```javascript
> new Date(1713350171)
1970-01-20T19:55:50.171Z
```
Something is off. The integer that you pass to `new Date()` needs to be the
_number of milliseconds_ since the unix epoch. We can get there by multiplying
our _seconds_ value by `1000`.
```javascript
> new Date(1713350171 * 1000)
2024-04-17T10:36:11.000Z
```
Not only can we, as humans, read that date, but we have a `Date` object that we
can use within our program.
Note: if you execute `Date.now()`, the value you get is in milliseconds.