diff()
Learn how to calculate differences between dates using the diff() method. Calculate age, duration, time elapsed, and date differences in years, months, weeks, days, hours, minutes, seconds, and milliseconds with practical examples for deadline warnings, relative time, working hours, and subscription duration tracking.
Calculates the difference between this date and another date.
Syntax
.diff(other: FduInstance, unit?: UnitType): numberParameters
other: FduInstance- Date to compare withunit?: UnitType- Unit for the difference (default: 'millisecond')
Returns
number - Numeric difference in the specified unit
Examples
Basic Difference
import { fdu } from '@pyyupsk/fdu';
const date1 = fdu('2024-01-15');
const date2 = fdu('2024-01-20');
// Days
date1.diff(date2, 'day'); // -5
date2.diff(date1, 'day'); // 5
// Default (milliseconds)
date1.diff(date2); // -432000000Different Units
const start = fdu('2024-01-01');
const end = fdu('2024-03-15');
end.diff(start, 'year'); // 0 (less than a year)
end.diff(start, 'month'); // 2 (2 months and 14 days)
end.diff(start, 'week'); // 10 (10 full weeks)
end.diff(start, 'day'); // 74Time Differences
const morning = fdu('2024-01-15T09:00:00');
const afternoon = fdu('2024-01-15T14:30:00');
afternoon.diff(morning, 'hour'); // 5
afternoon.diff(morning, 'minute'); // 330 (5.5 hours = 330 minutes)
afternoon.diff(morning, 'second'); // 19800Year and Month Differences
For years and months, the difference is calculated based on calendar units:
const date1 = fdu('2024-01-15');
const date2 = fdu('2025-01-10');
// Year difference (calendar years)
date2.diff(date1, 'year'); // 1 (different calendar years)
const date3 = fdu('2024-01-15');
const date4 = fdu('2024-03-20');
// Month difference (calendar months)
date4.diff(date3, 'month'); // 2 (from January to March)Supported Units
| Unit | Description |
|---|---|
year / y | Calendar years |
month / M | Calendar months |
week / w | 7-day periods |
day / d | 24-hour periods |
hour / h | 60-minute periods |
minute / m | 60-second periods |
second / s | 1000-millisecond periods |
millisecond / ms | Milliseconds (default) |
Common Patterns
Calculate age
const birthdate = fdu('1990-05-15');
const today = fdu();
const age = today.diff(birthdate, 'year');
console.log(`Age: ${age} years`);Days until event
const event = fdu('2024-12-25');
const now = fdu();
const daysUntil = event.diff(now, 'day');
console.log(`${daysUntil} days until Christmas`);Time elapsed
const start = fdu('2024-01-15T09:00:00');
const end = fdu('2024-01-15T14:30:45');
const hours = end.diff(start, 'hour');
const minutes = end.diff(start, 'minute');
const seconds = end.diff(start, 'second');
console.log(`Elapsed: ${hours}h ${minutes % 60}m ${seconds % 60}s`);
// Elapsed: 5h 30m 45sDuration in multiple units
function formatDuration(start: FduInstance, end: FduInstance): string {
const days = end.diff(start, 'day');
const hours = end.diff(start, 'hour') % 24;
const minutes = end.diff(start, 'minute') % 60;
return `${days}d ${hours}h ${minutes}m`;
}
const start = fdu('2024-01-15T09:00:00');
const end = fdu('2024-01-17T14:30:00');
formatDuration(start, end); // '2d 5h 30m'Relative time
function getRelativeTime(date: FduInstance): string {
const now = fdu();
const diffMinutes = now.diff(date, 'minute');
if (diffMinutes < 1) return 'just now';
if (diffMinutes < 60) return `${diffMinutes} minutes ago`;
const diffHours = now.diff(date, 'hour');
if (diffHours < 24) return `${diffHours} hours ago`;
const diffDays = now.diff(date, 'day');
if (diffDays < 7) return `${diffDays} days ago`;
const diffWeeks = now.diff(date, 'week');
if (diffWeeks < 4) return `${diffWeeks} weeks ago`;
const diffMonths = now.diff(date, 'month');
return `${diffMonths} months ago`;
}
const pastDate = fdu('2024-01-10');
getRelativeTime(pastDate); // e.g., '5 days ago'Deadline warning
const deadline = fdu('2024-12-31');
const now = fdu();
const daysRemaining = deadline.diff(now, 'day');
if (daysRemaining < 0) {
console.log(`Overdue by ${Math.abs(daysRemaining)} days`);
} else if (daysRemaining < 7) {
console.log(`Urgent: ${daysRemaining} days remaining`);
} else {
console.log(`${daysRemaining} days until deadline`);
}Working hours calculation
const clockIn = fdu('2024-01-15T09:00:00');
const clockOut = fdu('2024-01-15T17:30:00');
const hoursWorked = clockOut.diff(clockIn, 'hour');
const minutesWorked = clockOut.diff(clockIn, 'minute') % 60;
console.log(`Worked: ${hoursWorked} hours ${minutesWorked} minutes`);
// Worked: 8 hours 30 minutesSubscription duration
const subscriptionStart = fdu('2023-01-15');
const now = fdu();
const monthsSubscribed = now.diff(subscriptionStart, 'month');
const daysSubscribed = now.diff(subscriptionStart, 'day');
console.log(`Subscribed for ${monthsSubscribed} months (${daysSubscribed} days)`);Precision Notes
For year and month units, .diff() calculates based on calendar units, not elapsed time. For example, the difference between Dec 31, 2023 and Jan 1, 2024 is 1 year, even though it's only 1 day apart.
const date1 = fdu('2023-12-31');
const date2 = fdu('2024-01-01');
date2.diff(date1, 'year'); // 1 (different calendar years)
date2.diff(date1, 'day'); // 1 (actual days)See Also
- add() - Add time to a date
- subtract() - Subtract time from a date
- isBefore() - Check if before another date
- isAfter() - Check if after another date
isSame()
Master the isSame() method to compare dates with granular precision. Check if dates match by year, month, day, hour, minute, or second. Filter events, validate birthdays, check if today, group dates by month, and implement same time of day checks with practical examples.
Query
Master date querying methods to extract individual components from date instances. Learn how to get year, month, day, hour, minute, second, and millisecond values with practical examples for checking weekends, validating dates, building time objects, and implementing common date patterns.