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

Add Parse A Date From A Timestamp as a JavaScript til

This commit is contained in:
jbranchaud
2021-04-15 10:10:57 -05:00
parent 95cb87045b
commit c522530d12
2 changed files with 35 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://tinyletter.com/jbranchaud).
_1115 TILs and counting..._
_1116 TILs and counting..._
---
@@ -400,6 +400,7 @@ _1115 TILs and counting..._
- [Numbers Are Empty](javascript/numbers-are-empty.md)
- [Object Initialization With Shorthand Property Names](javascript/object-initialization-with-shorthand-property-names.md)
- [Obtain Undefined Value With The Void Operator](javascript/obtain-undefined-value-with-the-void-operator.md)
- [Parse A Date From A Timestamp](javascript/parse-a-date-from-a-timestamp.md)
- [Random Cannot Be Seeded](javascript/random-cannot-be-seeded.md)
- [Reach Into An Object For Nested Data With Get](javascript/reach-into-an-object-for-nested-data-with-get.md)
- [Render An Array Of Elements With React 16](javascript/render-an-array-of-elements-with-react-16.md)

View File

@@ -0,0 +1,33 @@
# Parse A Date From A Timestamp
If you are given a timestamp ([seconds since the Unix
epoch](https://stackoverflow.com/a/20823376/535590)) and you try to parse it
with [JavaScript's `new
Date()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date),
you are going to get a suprising result.
```javascript
> new Date(1618499080)
Mon Jan 19 1970 11:34:59 GMT-0600 (Central Standard Time)
```
1970? I was expected something more in the current millenia.
This is because JavaScript's `new Date()` expects a timestamp to be in milliseconds. Passing in a seconds representation of a timestamp, when it should be milliseconds, is going to result in a time pretty near the original Unix epoch.
Instead what you need to do is multiple that _seconds_ value by `1000` to get
it in terms of milliseconds.
```javascript
> new Date(1618499080 * 1000)
Thu Apr 15 2021 10:04:40 GMT-0500 (Central Daylight Time)
```
Also, notice that if I run [`+ new
Date()`](https://stackoverflow.com/a/221297/535590) without any argument, it
provides the current timestamp in milliseconds.
```javascript
> + new Date()
1618499080598
```