DEV Community

Cover image for Day 8: D-8 🎱
Valeria
Valeria

Posted on

Day 8: D-8 🎱

Do you know how many days left till Christmas? Well this little handy library certainly does!

Among other things it allows adding dates, calculating intervals and, of course, formatting dates.

Install it with e.g. deno add npm:date-fns and use like so:

import { formatDistanceToNow } from "npm:date-fns";
const xMas = new Date("2024-12-25");
console.log(`Christmas is ${formatDistanceToNow(xMas, { addSuffix: true })}`);
Enter fullscreen mode Exit fullscreen mode

Run it with e.g. deno run -A main.ts and you should get something like this:

deno run -A ./main.ts
Christmas is in 17 days
Enter fullscreen mode Exit fullscreen mode

You can also do things like:

formatDistanceToNow(addDays(new Date(),3), { addSuffix: true }); // in 3 days
formatDistanceToNow(addDays(new Date(),-3), { addSuffix: true }); // 3 days ago
format(new Date(),'yyyy-M-dd'); // 2024-12-08
Enter fullscreen mode Exit fullscreen mode

And a top of that you can also translate it to a localized string:

import { formatRelative, addHours, addDays } from "npm:date-fns";
import { sv, enUS } from "npm:date-fns/locale";

console.log(
  formatRelative(addHours(new Date(), 1), new Date(), { locale: sv })
);

console.log(
  formatRelative(addDays(new Date(), 1), new Date(), { locale: enUS })
);
Enter fullscreen mode Exit fullscreen mode

Which would get you something like:

deno run -A ./main.ts
# idag kl. 21:09
# tomorrow at 8:09 PM
Enter fullscreen mode Exit fullscreen mode

Liked the content and would love to have more of it all year long?

Buy Me A Coffee

Top comments (0)