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

Add Easy Date Comparison With DayJS as a javascript til

This commit is contained in:
jbranchaud
2018-11-09 09:31:12 -06:00
parent 19c01dd7a0
commit 57a06fd7af
2 changed files with 25 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_718 TILs and counting..._
_719 TILs and counting..._
---
@@ -247,6 +247,7 @@ _718 TILs and counting..._
- [Default And Named Exports From The Same Module](javascript/default-and-named-exports-from-the-same-module.md)
- [Destructuring The Rest Of An Array](javascript/destructuring-the-rest-of-an-array.md)
- [Enable ES7 Transforms With react-rails](javascript/enable-es7-transforms-with-react-rails.md)
- [Easy Date Comparison With DayJS](javascript/easy-date-comparison-with-dayjs.md)
- [Expand Emojis With The Spread Operator](javascript/expand-emojis-with-the-spread-operator.md)
- [Fill An Input With A Ton Of Text](javascript/fill-an-input-with-a-ton-of-text.md)
- [Freeze An Object, Sorta](javascript/freeze-an-object-sorta.md)

View File

@@ -0,0 +1,23 @@
# Easy Date Comparison With DayJS
Let's say my application fetches dates from the server which come back in
string form as `"YYYY-MM-DD"` and I'd like to know if those dates already
passed. This can be done easily by wrapping dates in
[DayJS](https://github.com/iamkun/dayjs) and using its comparison functions.
```javascript
import dayjs from 'dayjs';
const today = dayjs(new Date());
const pastDate = dayjs("2018-10-22");
const futureDate = dayjs("2022-01-01");
console.log(pastDate.isBefore(today));
// => true
console.log(futureDate.isBefore(today));
// => false
```
The `dayjs()` function can be used to construct DayJS date objects from Date
objects and strings. These can then be compared with functions like
`isBefore()` and `isAfter()`.