/alpine-timeago

⏱ Simple Alpine.js plugin to display the human-readable distance between a date and now.

Primary LanguageJavaScriptMIT LicenseMIT

⏱ Alpine TimeAgo ⏱

An Alpine.js plugin to return the distance between a given date and now in words (like "3 months ago", "about 2 hours ago" or "in about 5 hours").

version Build size JSDelivr GitHub Gitmoji

🚀 Installation

CDN

Include the following <script> tag in the <head> of your document, just before Alpine.

<script src="https://cdn.jsdelivr.net/npm/@marcreichel/alpine-timeago@latest/dist/alpine-timeago.min.js" defer></script>

NPM

npm install @marcreichel/alpine-timeago

Add the x-timeago directive to your project by importing the package before Alpine.js.

import Alpine from 'alpinejs';
import TimeAgo from '@marcreichel/alpine-timeago';

Alpine.plugin(TimeAgo);

window.Alpine = Alpine;
window.Alpine.start();

🪄 Usage

To convert a Date to the human-readable distance from now, add the x-data and x-timeago directives to an element and pass the date (as a Date or a string in ISO format) to the x-timeago directive. The directive will update the output every 30 seconds.

<span x-data="{ date: new Date() }" x-timeago="date"></span>

Under the hood the directive is using formatDistanceToNow from date-fns.

No suffix

If you do not want the "[diff] ago" suffix or "in [diff]" prefix, you can use the x-timeago.pure modifier.

<span x-data="{ date: new Date() }" x-timeago.pure="date"></span>

Other locales

If you are using the npm installation method for this package or the ESM distribution, you can use the TimeAgo.configure() method to provide a different locale from date-fns.

import TimeAgo from '@marcreichel/alpine-timeago';
import { de } from 'date-fns/locale';

Alpine.plugin(TimeAgo.configure({
    locale: de,
}));

📄 License

Copyright (c) 2022 Marc Reichel and contributors.

Licensed under the MIT license, see LICENSE for details.