DEV Community

Rafa Rafael
Rafa Rafael

Posted on

2

Date Formatting: Carbon, date-fns, and Vanilla JS

Working with dates and times is an essential part of web development. Whether you're building a blog, an e-commerce site, or a personal project, handling and formatting dates correctly can greatly enhance user experience. In this blog, we'll explore date formatting using three different methods: Carbon (PHP), date-fns (JavaScript), and Vanilla JS Date. We'll provide examples for each to help you understand how to format dates in various contexts.

1. Carbon (PHP)

Carbon is a popular PHP library that extends the native DateTime class to provide an easier and more intuitive API for date and time manipulation.

Installation

composer require nesbot/carbon
Enter fullscreen mode Exit fullscreen mode

Examples

Carbon provides extensive support for date formatting. Below are examples using different format patterns:

Basic Date Formatting:

use Carbon\Carbon;

$date = Carbon::now();
echo $date->format('Y-m-d'); // Output: 2024-05-17
Enter fullscreen mode Exit fullscreen mode

Time Formatting:

use Carbon\Carbon;

$date = Carbon::now();
echo $date->format('H:i:s'); // Output: 14:35:12 (example time)
Enter fullscreen mode Exit fullscreen mode

Full Date and Time Formatting:

use Carbon\Carbon;

$date = Carbon::now();
echo $date->format('Y-m-d H:i:s'); // Output: 2024-05-17 14:35:12
Enter fullscreen mode Exit fullscreen mode

Custom Date Formats:

use Carbon\Carbon;

$date = Carbon::create(2024, 5, 17);
echo $date->format('l, F j, Y'); // Output: Friday, May 17, 2024
Enter fullscreen mode Exit fullscreen mode

Different Date Components:

use Carbon\Carbon;

$date = Carbon::create(2024, 5, 17);
echo $date->format('D'); // Output: Fri
echo $date->format('d'); // Output: 17
echo $date->format('M'); // Output: May
echo $date->format('m'); // Output: 05
echo $date->format('Y'); // Output: 2024
echo $date->format('y'); // Output: 24
Enter fullscreen mode Exit fullscreen mode

Relative Time Formatting:

use Carbon\Carbon;

$date = Carbon::now()->subDays(3);
echo $date->diffForHumans(); // Output: 3 days ago
Enter fullscreen mode Exit fullscreen mode

2. date-fns (JavaScript)

date-fns is a modern JavaScript date utility library that provides a comprehensive set of functions for working with dates.

Installation

npm install date-fns
Enter fullscreen mode Exit fullscreen mode

Examples

date-fns offers a comprehensive set of formatting functions. Below are examples using different format patterns:

Basic Date Formatting:

import { format } from 'date-fns';

const date = new Date();
console.log(format(date, 'yyyy-MM-dd')); // Output: 2024-05-17
Enter fullscreen mode Exit fullscreen mode

Time Formatting:

import { format } from 'date-fns';

const date = new Date();
console.log(format(date, 'HH:mm:ss')); // Output: 14:35:12 (example time)
Enter fullscreen mode Exit fullscreen mode

Full Date and Time Formatting:

import { format } from 'date-fns';

const date = new Date();
console.log(format(date, 'yyyy-MM-dd HH:mm:ss')); // Output: 2024-05-17 14:35:12
Enter fullscreen mode Exit fullscreen mode

Custom Date Formats:

import { format } from 'date-fns';

const date = new Date(2024, 4, 17); // Note: Months are 0-indexed
console.log(format(date, 'EEEE, MMMM do, yyyy')); // Output: Friday, May 17th, 2024
Enter fullscreen mode Exit fullscreen mode

Different Date Components:

import { format } from 'date-fns';

const date = new Date(2024, 4, 17);
console.log(format(date, 'EEE')); // Output: Fri
console.log(format(date, 'dd')); // Output: 17
console.log(format(date, 'MMM')); // Output: May
console.log(format(date, 'MM')); // Output: 05
console.log(format(date, 'yyyy')); // Output: 2024
console.log(format(date, 'yy')); // Output: 24
Enter fullscreen mode Exit fullscreen mode

Relative Time Formatting:

import { formatDistance, subDays } from 'date-fns';

const date = subDays(new Date(), 3);
console.log(formatDistance(date, new Date(), { addSuffix: true })); // Output: 3 days ago
Enter fullscreen mode Exit fullscreen mode

3. Vanilla JS Date

Vanilla JavaScript's Date object provides basic methods for date and time manipulation without any dependencies.

Examples

Vanilla JavaScript Date provides basic methods for date formatting. Below are examples using different format patterns:

Basic Date Formatting:

const date = new Date();
const formattedDate = date.toISOString().split('T')[0];
console.log(formattedDate); // Output: 2024-05-17
Enter fullscreen mode Exit fullscreen mode

Time Formatting:

const date = new Date();
const formattedTime = date.toTimeString().split(' ')[0];
console.log(formattedTime); // Output: 14:35:12 (example time)
Enter fullscreen mode Exit fullscreen mode

Full Date and Time Formatting:

const date = new Date();
const formattedDateTime = `${date.toISOString().split('T')[0]} ${date.toTimeString().split(' ')[0]}`;
console.log(formattedDateTime); // Output: 2024-05-17 14:35:12
Enter fullscreen mode Exit fullscreen mode

Custom Date Formats:

const date = new Date(2024, 4, 17); // Note: Months are 0-indexed
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(date.toLocaleDateString('en-US', options)); // Output: Friday, May 17, 2024
Enter fullscreen mode Exit fullscreen mode

Different Date Components:

const date = new Date(2024, 4, 17); // Note: Months are 0-indexed
console.log(date.toDateString().split(' ')[0]); // Output: Fri
console.log(date.getDate()); // Output: 17
console.log(date.toLocaleString('default', { month: 'short' })); // Output: May
console.log(('0' + (date.getMonth() + 1)).slice(-2)); // Output: 05
console.log(date.getFullYear()); // Output: 2024
console.log(date.getFullYear().toString().slice(-2)); // Output: 24
Enter fullscreen mode Exit fullscreen mode

Relative Time Formatting:

const date = new Date();
const daysAgo = new Date(date.setDate(date.getDate() - 3));
const diffTime = Math.abs(new Date() - daysAgo);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(`${diffDays} days ago`); // Output: 3 days ago
Enter fullscreen mode Exit fullscreen mode

By using these libraries and methods, you can handle date formatting effectively across different programming environments, ensuring that your applications display dates and times in a user-friendly and consistent manner.

Enjoy!

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay