CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sugar

A comprehensive JavaScript utility library for working with native objects that extends Array, Date, Function, Number, Object, RegExp, and String with powerful methods.

Pending
Overview
Eval results
Files

date.mddocs/

Date Module

The Sugar Date module provides comprehensive date manipulation, formatting, and internationalization capabilities. With over 150 methods, it offers complete date/time functionality including creation, manipulation, comparison, calculation, formatting, and locale support.

Core Imports

import Sugar from "sugar";

// Enable Date methods
Sugar.extend();

// Or import specific date functionality
import Sugar from "sugar/date";

For CommonJS:

const Sugar = require("sugar");
Sugar.extend();

// Or specific module
const Sugar = require("sugar/date");

Basic Usage

import Sugar from "sugar";
Sugar.extend();

// Create dates from various inputs
const date1 = Sugar.Date.create("next Friday");
const date2 = Sugar.Date.create("2025-12-25");
const date3 = Sugar.Date.create("3 days ago");

// Date manipulation
const future = Sugar.Date.addDays(Sugar.Date.beginningOfWeek(Sugar.Date.addDays(date1, 5)));
const past = Sugar.Date.rewind(Sugar.Date.create(), "3 weeks 2 days");

// Formatting
const formatted = Sugar.Date.format(date1, "MMM dd, yyyy");
const relative = Sugar.Date.relative(date2); // "in 3 months"

// Comparisons and tests
const isWeekend = Sugar.Date.isWeekend(date1);
const isFuture = Sugar.Date.isFuture(date2);
const daysBetween = Sugar.Date.daysSince(date1, date2);

Capabilities

Date Creation and Configuration

Date creation from various input formats and locale management.

/**
 * Creates a date from various input types with optional configuration
 * @param d - Date input (string, number, Date, or undefined for now)
 * @param options - Creation options
 * @returns New Date instance
 */
function create(d?: any, options?: DateCreateOptions): Date;

/**
 * Creates a date range between two dates
 * @param start - Start date (any valid date input)
 * @param end - End date (any valid date input)  
 * @returns Range object containing date range
 */
function range(start?: any, end?: any): Range;

/**
 * Adds a custom locale for date parsing and formatting
 * @param localeCode - Locale identifier (e.g. "en-US")
 * @param def - Locale definition object
 */
function addLocale(localeCode: string, def: any): void;

/**
 * Gets all available locale codes
 * @returns Array of locale code strings
 */
function getAllLocaleCodes(): string[];

/**
 * Gets all locale objects
 * @returns Array of locale objects
 */
function getAllLocales(): Locale[];

/**
 * Gets a specific locale object
 * @param localeCode - Locale code (defaults to current locale)
 * @returns Locale object or undefined
 */
function getLocale(localeCode?: string): Locale | undefined;

/**
 * Removes a custom locale
 * @param localeCode - Locale code to remove
 */
function removeLocale(localeCode: string): void;

/**
 * Sets the active locale for date operations
 * @param localeCode - Locale code to activate
 */
function setLocale(localeCode: string): void;

Usage Examples:

// Create dates from strings
const christmas = Sugar.Date.create("December 25, 2025");
const meeting = Sugar.Date.create("next Tuesday at 3pm");
const deadline = Sugar.Date.create("in 2 weeks");

// Create with options
const utcDate = Sugar.Date.create("2025-06-15", { fromUTC: true });
const pastPreferred = Sugar.Date.create("May", { past: true });

// Create ranges
const quarter = Sugar.Date.range("January 1", "March 31");
const week = Sugar.Date.range("last Monday", "next Sunday");

// Locale management
Sugar.Date.setLocale("fr");
const frenchDate = Sugar.Date.create("15 janvier 2025");

Date Manipulation

Methods for adding, subtracting, and setting date components.

/**
 * Adds days to a date
 * @param instance - Date instance
 * @param n - Number of days to add
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function addDays(instance: Date, n: number, reset?: boolean): Date;

/**
 * Adds hours to a date
 * @param instance - Date instance  
 * @param n - Number of hours to add
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function addHours(instance: Date, n: number, reset?: boolean): Date;

/**
 * Adds minutes to a date
 * @param instance - Date instance
 * @param n - Number of minutes to add
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function addMinutes(instance: Date, n: number, reset?: boolean): Date;

/**
 * Adds seconds to a date
 * @param instance - Date instance
 * @param n - Number of seconds to add
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function addSeconds(instance: Date, n: number, reset?: boolean): Date;

/**
 * Adds weeks to a date
 * @param instance - Date instance
 * @param n - Number of weeks to add
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function addWeeks(instance: Date, n: number, reset?: boolean): Date;

/**
 * Adds months to a date
 * @param instance - Date instance
 * @param n - Number of months to add
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function addMonths(instance: Date, n: number, reset?: boolean): Date;

/**
 * Adds years to a date
 * @param instance - Date instance
 * @param n - Number of years to add
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function addYears(instance: Date, n: number, reset?: boolean): Date;

/**
 * Advances a date by a time unit or compound string
 * @param instance - Date instance
 * @param set - Time unit object or string (e.g. "3 days 2 hours")
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function advance(instance: Date, set: any, reset?: boolean): Date;

/**
 * Rewinds a date by a time unit or compound string
 * @param instance - Date instance
 * @param set - Time unit object or string (e.g. "1 week 3 days")
 * @param reset - Reset smaller units to beginning  
 * @returns Modified date instance
 */
function rewind(instance: Date, set: any, reset?: boolean): Date;

/**
 * Sets specific date components
 * @param instance - Date instance
 * @param set - Object or string specifying what to set
 * @param reset - Reset smaller units to beginning
 * @returns Modified date instance
 */
function set(instance: Date, set: any, reset?: boolean): Date;

/**
 * Resets a date to the beginning of a time unit
 * @param instance - Date instance
 * @param unit - Time unit ("day", "week", "month", "year")
 * @param locale - Locale for week calculations
 * @returns Modified date instance
 */
function reset(instance: Date, unit?: string, locale?: string): Date;

Usage Examples:

const today = Sugar.Date.create();

// Add time units
const tomorrow = Sugar.Date.addDays(Sugar.Date.clone(today), 1);
const nextWeek = Sugar.Date.addWeeks(Sugar.Date.clone(today), 1);
const nextYear = Sugar.Date.addYears(Sugar.Date.clone(today), 1);

// Complex additions with reset
const startOfNextMonth = Sugar.Date.addMonths(Sugar.Date.clone(today), 1, true); // Resets to 1st day

// Advance/rewind with strings
const future = Sugar.Date.advance(Sugar.Date.clone(today), "2 weeks 3 days 4 hours");
const past = Sugar.Date.rewind(Sugar.Date.clone(today), "1 month 2 weeks");

// Set specific components
const newYear = Sugar.Date.set(Sugar.Date.clone(today), { month: 0, day: 1 }); // January 1st
const midnight = Sugar.Date.set(Sugar.Date.clone(today), { hour: 0, minute: 0, second: 0 });

// Reset to boundaries
const startOfWeek = Sugar.Date.reset(Sugar.Date.clone(today), "week");
const startOfMonth = Sugar.Date.reset(Sugar.Date.clone(today), "month");

Date Comparison

Methods for comparing dates and testing relationships.

/**
 * Tests if two dates are equal within an optional margin
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param margin - Margin of error in milliseconds
 * @returns True if dates are equal
 */
function is(instance: Date, date: any, margin?: number): boolean;

/**
 * Tests if date is after another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param margin - Margin of error in milliseconds
 * @returns True if date is after
 */
function isAfter(instance: Date, date: any, margin?: number): boolean;

/**
 * Tests if date is before another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param margin - Margin of error in milliseconds
 * @returns True if date is before
 */
function isBefore(instance: Date, date: any, margin?: number): boolean;

/**
 * Tests if date is between two other dates
 * @param instance - Date instance
 * @param start - Start date for range
 * @param end - End date for range
 * @param margin - Margin of error in milliseconds
 * @returns True if date is between start and end
 */
function isBetween(instance: Date, start: any, end: any, margin?: number): boolean;

Date Period Tests

Methods for testing if a date falls within specific time periods or has certain characteristics.

/**
 * Tests if date falls on a Monday
 * @param instance - Date instance
 * @returns True if date is Monday
 */
function isMonday(instance: Date): boolean;

/**
 * Tests if date falls on a Tuesday
 * @param instance - Date instance
 * @returns True if date is Tuesday
 */
function isTuesday(instance: Date): boolean;

/**
 * Tests if date falls on a Wednesday
 * @param instance - Date instance
 * @returns True if date is Wednesday
 */
function isWednesday(instance: Date): boolean;

/**
 * Tests if date falls on a Thursday
 * @param instance - Date instance
 * @returns True if date is Thursday
 */
function isThursday(instance: Date): boolean;

/**
 * Tests if date falls on a Friday
 * @param instance - Date instance
 * @returns True if date is Friday
 */
function isFriday(instance: Date): boolean;

/**
 * Tests if date falls on a Saturday
 * @param instance - Date instance
 * @returns True if date is Saturday
 */
function isSaturday(instance: Date): boolean;

/**
 * Tests if date falls on a Sunday
 * @param instance - Date instance
 * @returns True if date is Sunday
 */
function isSunday(instance: Date): boolean;

/**
 * Tests if date is in the future
 * @param instance - Date instance
 * @returns True if date is in the future
 */
function isFuture(instance: Date): boolean;

/**
 * Tests if date is in the past
 * @param instance - Date instance
 * @returns True if date is in the past
 */
function isPast(instance: Date): boolean;

/**
 * Tests if date is today
 * @param instance - Date instance
 * @returns True if date is today
 */
function isToday(instance: Date): boolean;

/**
 * Tests if date is tomorrow
 * @param instance - Date instance
 * @returns True if date is tomorrow
 */
function isTomorrow(instance: Date): boolean;

/**
 * Tests if date is yesterday
 * @param instance - Date instance
 * @returns True if date is yesterday
 */
function isYesterday(instance: Date): boolean;

/**
 * Tests if date is in the current week
 * @param instance - Date instance
 * @param locale - Locale for week calculation
 * @returns True if date is this week
 */
function isThisWeek(instance: Date, locale?: string): boolean;

/**
 * Tests if date is in the current month
 * @param instance - Date instance
 * @param locale - Locale for month calculation
 * @returns True if date is this month
 */
function isThisMonth(instance: Date, locale?: string): boolean;

/**
 * Tests if date is in the current year
 * @param instance - Date instance
 * @param locale - Locale for year calculation
 * @returns True if date is this year
 */
function isThisYear(instance: Date, locale?: string): boolean;

/**
 * Tests if date is in the last week
 * @param instance - Date instance
 * @param locale - Locale for week calculation
 * @returns True if date is last week
 */
function isLastWeek(instance: Date, locale?: string): boolean;

/**
 * Tests if date is in the last month
 * @param instance - Date instance
 * @param locale - Locale for month calculation
 * @returns True if date is last month
 */
function isLastMonth(instance: Date, locale?: string): boolean;

/**
 * Tests if date is in the last year
 * @param instance - Date instance
 * @param locale - Locale for year calculation
 * @returns True if date is last year
 */
function isLastYear(instance: Date, locale?: string): boolean;

/**
 * Tests if date is in the next week
 * @param instance - Date instance
 * @param locale - Locale for week calculation
 * @returns True if date is next week
 */
function isNextWeek(instance: Date, locale?: string): boolean;

/**
 * Tests if date is in the next month
 * @param instance - Date instance
 * @param locale - Locale for month calculation
 * @returns True if date is next month
 */
function isNextMonth(instance: Date, locale?: string): boolean;

/**
 * Tests if date is in the next year
 * @param instance - Date instance
 * @param locale - Locale for year calculation
 * @returns True if date is next year
 */
function isNextYear(instance: Date, locale?: string): boolean;

/**
 * Tests if date falls on a weekday (Monday-Friday)
 * @param instance - Date instance
 * @returns True if date is a weekday
 */
function isWeekday(instance: Date): boolean;

/**
 * Tests if date falls on a weekend (Saturday-Sunday)
 * @param instance - Date instance
 * @returns True if date is a weekend
 */
function isWeekend(instance: Date): boolean;

/**
 * Tests if date is in a leap year
 * @param instance - Date instance
 * @returns True if date is in a leap year
 */
function isLeapYear(instance: Date): boolean;

/**
 * Tests if date is in UTC
 * @param instance - Date instance
 * @returns True if date is UTC
 */
function isUTC(instance: Date): boolean;

/**
 * Tests if date is valid
 * @param instance - Date instance
 * @returns True if date is valid
 */
function isValid(instance: Date): boolean;

Date Calculations

Methods for calculating time differences between dates in various units.

/**
 * Gets the number of days from the date to now or another date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of days
 */
function daysAgo(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of days from now to the date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of days
 */
function daysFromNow(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of days since another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of days since date
 */
function daysSince(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of days until another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of days until date
 */
function daysUntil(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of hours from the date to now or another date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of hours
 */
function hoursAgo(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of hours from now to the date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of hours
 */
function hoursFromNow(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of hours since another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of hours since date
 */
function hoursSince(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of hours until another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of hours until date
 */
function hoursUntil(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of minutes from the date to now or another date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of minutes
 */
function minutesAgo(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of minutes from now to the date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of minutes
 */
function minutesFromNow(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of minutes since another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of minutes since date
 */
function minutesSince(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of minutes until another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of minutes until date
 */
function minutesUntil(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of seconds from the date to now or another date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of seconds
 */
function secondsAgo(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of seconds from now to the date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of seconds
 */
function secondsFromNow(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of seconds since another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of seconds since date
 */
function secondsSince(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of seconds until another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of seconds until date
 */
function secondsUntil(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of milliseconds from the date to now or another date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of milliseconds
 */
function millisecondsAgo(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of milliseconds from now to the date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of milliseconds
 */
function millisecondsFromNow(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of milliseconds since another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of milliseconds since date
 */
function millisecondsSince(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of milliseconds until another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of milliseconds until date
 */
function millisecondsUntil(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of weeks from the date to now or another date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of weeks
 */
function weeksAgo(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of weeks from now to the date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of weeks
 */
function weeksFromNow(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of weeks since another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of weeks since date
 */
function weeksSince(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of weeks until another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of weeks until date
 */
function weeksUntil(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of months from the date to now or another date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of months
 */
function monthsAgo(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of months from now to the date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of months
 */
function monthsFromNow(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of months since another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of months since date
 */
function monthsSince(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of months until another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of months until date
 */
function monthsUntil(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of years from the date to now or another date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of years
 */
function yearsAgo(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of years from now to the date
 * @param instance - Date instance
 * @param date - Date to compare with (defaults to now)
 * @param options - Calculation options
 * @returns Number of years
 */
function yearsFromNow(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of years since another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of years since date
 */
function yearsSince(instance: Date, date?: any, options?: any): number;

/**
 * Gets the number of years until another date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param options - Calculation options
 * @returns Number of years until date
 */
function yearsUntil(instance: Date, date?: any, options?: any): number;

Usage Examples:

const now = Sugar.Date.create();
const birthday = Sugar.Date.create("1990-05-15");
const meeting = Sugar.Date.create("next Friday at 2pm");

// Calculate differences
const age = Sugar.Date.yearsAgo(birthday); // 34 (years old)
const daysToMeeting = Sugar.Date.daysFromNow(meeting); // 3 (days until meeting)
const hoursSince = Sugar.Date.hoursSince(birthday); // ~298,440 (hours since birth)

// Compare specific dates
const project1 = Sugar.Date.create("2025-01-15");
const project2 = Sugar.Date.create("2025-03-01");
const monthsBetween = Sugar.Date.monthsUntil(project1, project2); // ~1.5 months

Date Formatting

Methods for converting dates to formatted strings for display.

/**
 * Formats a date using a format string with locale support
 * @param instance - Date instance
 * @param format - Format string (e.g. "MMM dd, yyyy")
 * @param locale - Locale code
 * @returns Formatted date string
 */
function format(instance: Date, format?: string, locale?: string): string;

/**
 * Formats date in full locale format
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Full formatted date string
 */
function full(instance: Date, locale?: string): string;

/**
 * Formats date in long locale format
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Long formatted date string
 */
function long(instance: Date, locale?: string): string;

/**
 * Formats date in medium locale format
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Medium formatted date string
 */
function medium(instance: Date, locale?: string): string;

/**
 * Formats date in short locale format
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Short formatted date string
 */
function short(instance: Date, locale?: string): string;

/**
 * Formats date in ISO 8601 format
 * @param instance - Date instance
 * @returns ISO formatted date string (YYYY-MM-DDTHH:mm:ss.sssZ)
 */
function iso(instance: Date): string;

/**
 * Formats date as a relative time string
 * @param instance - Date instance
 * @param locale - Locale code
 * @param relativeFn - Custom relative function
 * @returns Relative time string (e.g. "3 days ago", "in 2 hours")
 */
function relative(instance: Date, locale?: string, relativeFn?: Function): string;

/**
 * Formats date relative to another specific date
 * @param instance - Date instance
 * @param date - Date to compare with
 * @param locale - Locale code
 * @returns Relative time string
 */
function relativeTo(instance: Date, date: any, locale?: string): string;

Usage Examples:

const date = Sugar.Date.create("2025-06-15 14:30:00");

// Custom formatting
const custom = Sugar.Date.format(date, "MMM dd, yyyy 'at' h:mm a"); // "Jun 15, 2025 at 2:30 PM"
const european = Sugar.Date.format(date, "dd/MM/yyyy"); // "15/06/2025"
const time = Sugar.Date.format(date, "HH:mm:ss"); // "14:30:00"

// Predefined formats
const fullFormat = Sugar.Date.full(date); // "Sunday, June 15, 2025"
const longFormat = Sugar.Date.long(date); // "June 15, 2025"
const mediumFormat = Sugar.Date.medium(date); // "Jun 15, 2025"
const shortFormat = Sugar.Date.short(date); // "6/15/25"

// ISO format
const isoString = Sugar.Date.iso(date); // "2025-06-15T14:30:00.000Z"

// Relative formatting
const past = Sugar.Date.create("2 days ago");
const future = Sugar.Date.create("in 3 hours");
const relativeStr1 = Sugar.Date.relative(past); // "2 days ago"
const relativeStr2 = Sugar.Date.relative(future); // "in 3 hours"

// Relative to specific date
const birthday = Sugar.Date.create("1990-05-15");
const relativeAge = Sugar.Date.relativeTo(birthday, date); // "35 years ago"

Date Boundaries

Methods for finding the beginning and end of time periods.

/**
 * Gets the beginning of the day (midnight)
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Date at start of day
 */
function beginningOfDay(instance: Date, locale?: string): Date;

/**
 * Gets the beginning of the week
 * @param instance - Date instance
 * @param locale - Locale code (affects first day of week)
 * @returns Date at start of week
 */
function beginningOfWeek(instance: Date, locale?: string): Date;

/**
 * Gets the beginning of the month
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Date at start of month (1st day)
 */
function beginningOfMonth(instance: Date, locale?: string): Date;

/**
 * Gets the beginning of the year
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Date at start of year (January 1st)
 */
function beginningOfYear(instance: Date, locale?: string): Date;

/**
 * Gets the beginning of the ISO week (Monday)
 * @param instance - Date instance
 * @returns Date at start of ISO week
 */
function beginningOfISOWeek(instance: Date): Date;

/**
 * Gets the end of the day (23:59:59.999)
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Date at end of day
 */
function endOfDay(instance: Date, locale?: string): Date;

/**
 * Gets the end of the week
 * @param instance - Date instance
 * @param locale - Locale code (affects last day of week)
 * @returns Date at end of week
 */
function endOfWeek(instance: Date, locale?: string): Date;

/**
 * Gets the end of the month (last day)
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Date at end of month
 */
function endOfMonth(instance: Date, locale?: string): Date;

/**
 * Gets the end of the year (December 31st)
 * @param instance - Date instance
 * @param locale - Locale code
 * @returns Date at end of year
 */
function endOfYear(instance: Date, locale?: string): Date;

/**
 * Gets the end of the ISO week (Sunday)
 * @param instance - Date instance
 * @returns Date at end of ISO week
 */
function endOfISOWeek(instance: Date): Date;

Usage Examples:

const someDate = Sugar.Date.create("2025-06-15 14:30:00"); // A Sunday

// Beginning of periods
const dayStart = Sugar.Date.beginningOfDay(someDate); // "2025-06-15 00:00:00"
const weekStart = Sugar.Date.beginningOfWeek(someDate); // Previous Sunday 00:00:00
const monthStart = Sugar.Date.beginningOfMonth(someDate); // "2025-06-01 00:00:00"
const yearStart = Sugar.Date.beginningOfYear(someDate); // "2025-01-01 00:00:00"
const isoWeekStart = Sugar.Date.beginningOfISOWeek(someDate); // Previous Monday 00:00:00

// End of periods
const dayEnd = Sugar.Date.endOfDay(someDate); // "2025-06-15 23:59:59.999"
const weekEnd = Sugar.Date.endOfWeek(someDate); // Same Sunday 23:59:59.999
const monthEnd = Sugar.Date.endOfMonth(someDate); // "2025-06-30 23:59:59.999"
const yearEnd = Sugar.Date.endOfYear(someDate); // "2025-12-31 23:59:59.999"
const isoWeekEnd = Sugar.Date.endOfISOWeek(someDate); // Next Sunday 23:59:59.999

// Common patterns
const thisMonthRange = [Sugar.Date.beginningOfMonth(Sugar.Date.create()), Sugar.Date.endOfMonth(Sugar.Date.create())];
const thisWeekSchedule = Sugar.Date.daysUntil(Sugar.Date.addDays(Sugar.Date.beginningOfWeek(Sugar.Date.create()), 1), Sugar.Date.endOfWeek(Sugar.Date.create())); // Days in work week

Date Utilities

Utility methods for date manipulation, cloning, and information retrieval.

/**
 * Creates a copy of the date
 * @param instance - Date instance
 * @returns Cloned date instance
 */
function clone(instance: Date): Date;

/**
 * Gets the number of days in the current month
 * @param instance - Date instance
 * @returns Number of days in month (28-31)
 */
function daysInMonth(instance: Date): number;

/**
 * Parses and gets a date from various input formats
 * @param instance - Date instance
 * @param date - Date input to parse
 * @param options - Parse options
 * @returns Parsed date or original instance
 */
function get(instance: Date, date: any, options?: any): Date;

/**
 * Gets the ISO week number (1-53)
 * @param instance - Date instance
 * @returns ISO week number
 */
function getISOWeek(instance: Date): number;

/**
 * Gets the weekday number (0=Sunday, 1=Monday, etc.)
 * @param instance - Date instance
 * @returns Weekday number (0-6)
 */
function getWeekday(instance: Date): number;

/**
 * Gets the UTC weekday number
 * @param instance - Date instance
 * @returns UTC weekday number (0-6)
 */
function getUTCWeekday(instance: Date): number;

/**
 * Gets the UTC offset in minutes or ISO format
 * @param instance - Date instance
 * @param iso - Return in ISO format (+/-HH:MM)
 * @returns UTC offset in minutes or ISO string
 */
function getUTCOffset(instance: Date, iso?: boolean): number | string;

/**
 * Sets the ISO week number
 * @param instance - Date instance
 * @param value - ISO week number to set
 * @returns Modified date instance
 */
function setISOWeek(instance: Date, value: any): Date;

/**
 * Sets the weekday
 * @param instance - Date instance
 * @param value - Weekday to set (0-6 or name)
 * @returns Modified date instance
 */
function setWeekday(instance: Date, value: any): Date;

/**
 * Sets the date to UTC
 * @param instance - Date instance
 * @param value - Value to set for UTC conversion
 * @returns Modified date instance
 */
function setUTC(instance: Date, value: any): Date;

Usage Examples:

const original = Sugar.Date.create("2025-06-15");

// Clone for safe manipulation
const copy = Sugar.Date.clone(original);
Sugar.Date.addDays(copy, 5); // original is unchanged

// Date information
const daysInJune = Sugar.Date.daysInMonth(original); // 30
const weekNumber = Sugar.Date.getISOWeek(original); // 24 (24th week of year)
const dayOfWeek = Sugar.Date.getWeekday(original); // 0 (Sunday)

// UTC operations
const utcOffset = Sugar.Date.getUTCOffset(original); // -480 (minutes, varies by timezone)
const utcOffsetISO = Sugar.Date.getUTCOffset(original, true); // "-08:00" (ISO format)

// Set weekday
const nextMonday = Sugar.Date.setWeekday(Sugar.Date.clone(original), 1); // Set to Monday
const previousFriday = Sugar.Date.setWeekday(Sugar.Date.clone(original), -2); // Set to Friday (negative = previous)

// Set ISO week
const week20 = Sugar.Date.setISOWeek(Sugar.Date.clone(original), 20); // Move to 20th week of year

// Parse complex dates
const parsed1 = Sugar.Date.get(Sugar.Date.create(), "next Friday at 3pm");
const parsed2 = Sugar.Date.get(Sugar.Date.create(), "last day of March");

Types

/**
 * Options for date creation with parsing and timezone control
 */
interface DateCreateOptions {
  /** Locale code for parsing (e.g. "en-US", "fr") */
  locale?: string;
  /** Prefer past dates when parsing ambiguous inputs */
  past?: boolean;
  /** Prefer future dates when parsing ambiguous inputs */
  future?: boolean;
  /** Parse input as UTC time */
  fromUTC?: boolean;
  /** Set result as UTC time */
  setUTC?: boolean;
  /** Clone the input if it's already a Date */
  clone?: boolean;
}

/**
 * Locale interface for internationalization support
 */
interface Locale {
  /** Add a date format pattern */
  addFormat(src: string, to?: Array<string>): void;
  /** Get duration string for milliseconds */
  getDuration(ms: number): string;
  /** Get first day of week (0=Sunday, 1=Monday) */
  getFirstDayOfWeek(): number;
  /** Get first day of week year */
  getFirstDayOfWeekYear(): number;
  /** Get localized month name */
  getMonthName(n: number): string;
  /** Get localized weekday name */
  getWeekdayName(n: number): string;
}

/**
 * Range class for date ranges with iteration and manipulation
 */
interface Range {
  /** Clamp a date to this range */
  clamp<T>(el: T): T;
  /** Clone this range */
  clone(): Range;
  /** Test if date is contained in range */
  contains<T>(el: T): boolean;
  /** Iterate over range with specified interval */
  every<T>(amount: string | number, everyFn?: Function): T[];
  /** Get intersection with another range */
  intersect(range: Range): Range;
  /** Test if range is valid */
  isValid(): boolean;
  /** Get span of range */
  span(): number;
  /** Convert range to array */
  toArray<T>(): T[];
  /** Convert range to string */
  toString(): string;
  /** Get union with another range */
  union(range: Range): Range;
  
  // Date range specific methods
  /** Get range span in days */
  days(): number;
  /** Get range span in hours */
  hours(): number;
  /** Get range span in milliseconds */
  milliseconds(): number;
  /** Get range span in minutes */
  minutes(): number;
  /** Get range span in months */
  months(): number;
  /** Get range span in seconds */
  seconds(): number;
  /** Get range span in weeks */
  weeks(): number;
  /** Get range span in years */
  years(): number;
}

Locale System

Sugar Date includes comprehensive internationalization support with 18 built-in locales and the ability to add custom locales.

Built-in Locales

Available locale codes: ca (Catalan), da (Danish), de (German), es (Spanish), fi (Finnish), fr (French), it (Italian), ja (Japanese), ko (Korean), nl (Dutch), no (Norwegian), pl (Polish), pt (Portuguese), ru (Russian), sv (Swedish), zh-CN (Chinese Simplified), zh-TW (Chinese Traditional).

Usage Examples:

// Set global locale
Sugar.Date.setLocale("fr");
const frenchDate = Sugar.Date.create("15 janvier 2025"); // French input
const frenchFormat = Sugar.Date.format(frenchDate, "d MMMM yyyy"); // "15 janvier 2025"

// Per-operation locale
const germanFormat = Sugar.Date.format(Sugar.Date.create(), "d. MMMM yyyy", "de"); // "15. Januar 2025"
const spanishRelative = Sugar.Date.relative(Sugar.Date.create("yesterday"), "es"); // "ayer"

// Week calculations with locale
Sugar.Date.setLocale("en-US"); // Week starts Sunday
const usWeekStart = Sugar.Date.beginningOfWeek(Sugar.Date.create()); // Previous/current Sunday

Sugar.Date.setLocale("de"); // Week starts Monday  
const germanWeekStart = Sugar.Date.beginningOfWeek(Sugar.Date.create()); // Previous/current Monday

// Custom locale
Sugar.Date.addLocale("en-custom", {
  months: ["Jan", "Feb", "Mar", /*...*/],
  weekdays: ["Sun", "Mon", "Tue", /*...*/],
  formats: {
    "short": "M/d/yy",
    "medium": "MMM d, yyyy"
  }
});

Sugar.Date.setLocale("en-custom");
const customFormat = Sugar.Date.medium(Sugar.Date.create()); // Uses custom medium format

Common Patterns

Date Validation and Error Handling

// Safe date creation
function createSafeDate(input: any): Date | null {
  try {
    const date = Sugar.Date.create(input);
    return Sugar.Date.isValid(date) ? date : null;
  } catch (e) {
    return null;
  }
}

// Validate date ranges
function isValidRange(start: any, end: any): boolean {
  const startDate = Sugar.Date.create(start);
  const endDate = Sugar.Date.create(end);
  return Sugar.Date.isValid(startDate) && Sugar.Date.isValid(endDate) && !Sugar.Date.isAfter(startDate, endDate);
}

Business Date Calculations

// Add business days (skip weekends)
function addBusinessDays(date: Date, days: number): Date {
  const result = Sugar.Date.clone(date);
  let remaining = days;
  
  while (remaining > 0) {
    Sugar.Date.addDays(result, 1);
    if (Sugar.Date.isWeekday(result)) {
      remaining--;
    }
  }
  
  return result;
}

// Get next business day
function nextBusinessDay(date: Date): Date {
  const next = Sugar.Date.addDays(Sugar.Date.clone(date), 1);
  return Sugar.Date.isWeekend(next) ? nextBusinessDay(next) : next;
}

// Calculate age in years
function calculateAge(birthDate: Date): number {
  return Math.floor(Sugar.Date.yearsAgo(birthDate));
}

Date Formatting Utilities

// Smart relative formatting
function smartRelative(date: Date): string {
  const now = Sugar.Date.create();
  const daysDiff = Math.abs(Sugar.Date.daysUntil(date, now));
  
  if (daysDiff === 0) return "Today";
  if (daysDiff === 1) return Sugar.Date.isBefore(date, now) ? "Yesterday" : "Tomorrow";
  if (daysDiff < 7) return Sugar.Date.relative(date);
  if (daysDiff < 365) return Sugar.Date.format(date, "MMM d");
  return Sugar.Date.format(date, "MMM d, yyyy");
}

// Consistent date display
function displayDate(date: Date, context: "list" | "detail" | "relative"): string {
  switch (context) {
    case "list": return Sugar.Date.format(date, "M/d/yyyy");
    case "detail": return Sugar.Date.format(date, "EEEE, MMMM d, yyyy 'at' h:mm a");
    case "relative": return smartRelative(date);
    default: return date.toString();
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-sugar

docs

array.md

date.md

function.md

index.md

localization.md

number.md

object.md

range.md

regexp.md

string.md

tile.json