Files
30-seconds-of-code/snippets/getTimestamp.md
Isabelle Viktoria Maciohsek 8bf67754ce Make expertise a field
2022-03-01 20:21:45 +02:00

22 lines
587 B
Markdown

---
title: Unix timestamp from date
tags: date
expertise: beginner
firstSeen: 2020-10-08T17:15:56+03:00
lastUpdated: 2020-10-19T22:49:51+03:00
---
Gets the Unix timestamp from a `Date` object.
- Use `Date.prototype.getTime()` to get the timestamp in milliseconds and divide by `1000` to get the timestamp in seconds.
- Use `Math.floor()` to appropriately round the resulting timestamp to an integer.
- Omit the argument, `date`, to use the current date.
```js
const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000);
```
```js
getTimestamp(); // 1602162242
```