DEV Community

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

Posted on

2

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more