Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Practical Techniques for Efficient Date and Time Handling with Day.js

Tech 1

Day.js is a lightweight JavaScript library for parsing, manipulating, and formatting dates and times. Its minimal footprint and intuitive API make it a preferred choice for date-related operations.

Installation

Using npm

npm install dayjs

Usage:

import dayjs from 'dayjs';
console.log(dayjs()); // Logs the current date and time

Using a CDN

Include the library via a script tag.

<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script>
  console.log(dayjs());
</script>

Date Formatting

The .format() method converts a dayjs object into a readable string. Without arguments, it returns an ISO-like string.

dayjs().format(); // e.g., '2023-05-01T14:30:00+08:00'

Custom formats are created using tokens. Common tokens include YYYY (year), MM (month), DD (day), HH (24-hour), hh (12-hour), mm (minutes), ss (seconds), SSS (milliseconds).

// Current date in various formats
console.log(dayjs().format('YYYY-MM-DD'));           // '2023-05-01'
console.log(dayjs().format('DD/MM/YYYY'));           // '01/05/2023'
console.log(dayjs().format('YYYY年MM月DD日 HH:mm')); // '2023年05月01日 14:30'

// Format a specific date
const eventDate = dayjs('2023-12-25');
console.log(eventDate.format('dddd, MMMM D, YYYY')); // 'Monday, December 25, 2023'

Getting and Setting Date Components

Methods like .year(), .month(), .date(), .hour() retrieve or modify specific parts of a date.

const today = dayjs();
// Get components
const currentYear = today.year();   // 2023
const currentMonth = today.month(); // Returns 0-11 (0 = January)
const currentDate = today.date();   // Day of the month

// Set components (returns a new dayjs object)
const nextYear = today.year(2024);
const lastDayOfMonth = today.date(31);

// Chain setting and formatting
const modified = dayjs().month(10).date(15).format('YYYY-MM-DD');
console.log(modified);

Date Calculations

Adding Time

Use .add(value, unit) to add time. Common units: day, week, month, year, hour, minute, second.

// Add 10 days to the current date
const inTenDays = dayjs().add(10, 'day');
console.log(inTenDays.format('YYYY-MM-DD'));

// Add 90 minutes
const laterTime = dayjs().add(90, 'minute');

// Add 2.5 hours using decimal
const later = dayjs().add(2.5, 'hour');

Subtracting Time

Use .subtract(value, unit) to subtract time.

// One week ago
const lastWeek = dayjs().subtract(7, 'day');
console.log(lastWeek.format('YYYY-MM-DD'));

Getting Start and End of a Period

The .startOf(unit) and .endOf(unit) methods are useful for calculating ranges.

// Start and end of the current month
const monthStart = dayjs().startOf('month').format();
const monthEnd = dayjs().endOf('month').format();

// Start of the current week (locale-dependent)
const weekStart = dayjs().startOf('week').format('YYYY-MM-DD');

// End of the current day (23:59:59.999)
const dayEnd = dayjs().endOf('day').format('HH:mm:ss');

Calculating Differences

The .diff(target, unit) method calculates the difference between two dates.

const past = dayjs('2020-01-01');
const now = dayjs();

// Default difference in milliseconds
const msDiff = now.diff(past);

// Difference in specific units
const yearsDiff = now.diff(past, 'year');
const daysDiff = now.diff(past, 'day');
const hoursDiff = now.diff(past, 'hour');

Date Queries

Days in a Month

Use .daysInMonth() to get the number of days.

const daysInFeb2023 = dayjs('2023-02').daysInMonth(); // 28
const daysInFeb2008 = dayjs('2008-02').daysInMonth(); // 29

Comparisons

Methods like .isBefore(), .isAfter(), and .isSame() are used for date comparisons. They optionally accept a unit for granular comparison.

const referenceDate = dayjs('2023-06-01');
const checkDate = dayjs('2023-05-20');

// Simple comparisons
console.log(checkDate.isBefore(referenceDate)); // true
console.log(checkDate.isAfter(referenceDate));  // false

// Comparison with a unit (e.g., same month?)
console.log(checkDate.isSame(referenceDate, 'month')); // false (May vs June)

// Check if a date is within a range using logical operators
const startRange = dayjs('2023-01-01');
const endRange = dayjs('2023-12-31');
const testDate = dayjs('2023-07-04');
const isInRange = testDate.isAfter(startRange) && testDate.isBefore(endRange);
console.log(isInRange); // true

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.