From 57a06fd7af6d4b1a63541528689d00f9f2c0ca1f Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 9 Nov 2018 09:31:12 -0600 Subject: [PATCH] Add Easy Date Comparison With DayJS as a javascript til --- README.md | 3 ++- javascript/easy-date-comparison-with-dayjs.md | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 javascript/easy-date-comparison-with-dayjs.md diff --git a/README.md b/README.md index 5751fff..c530141 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/javascript/easy-date-comparison-with-dayjs.md b/javascript/easy-date-comparison-with-dayjs.md new file mode 100644 index 0000000..6013655 --- /dev/null +++ b/javascript/easy-date-comparison-with-dayjs.md @@ -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()`.