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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay