Skip to main content
The app-datepicker library provides a comprehensive set of helper functions for date manipulation, validation, and calendar operations. These utilities are used internally by the components and can also be imported for custom use cases.

Date Validation

dateValidator

Validates a date value and returns validation result with a fallback date.
function dateValidator(value: MaybeDate, defaultDate: Date): DateValidatorResult
value
MaybeDate
The date value to validate (can be Date, string, number, or null)
defaultDate
Date
Fallback date to return if validation fails
date
Date
The validated date or the default date if invalid
isValid
boolean
Whether the input date was valid
Example:
import { dateValidator } from 'app-datepicker/helpers/date-validator.js';

const result = dateValidator('2024-01-15', new Date());
console.log(result.isValid); // true
console.log(result.date); // Date object for 2024-01-15

const invalid = dateValidator('invalid', new Date());
console.log(invalid.isValid); // false
console.log(invalid.date); // Today's date (fallback)

Date Conversion

toResolvedDate

Converts various date formats to a normalized UTC Date object.
function toResolvedDate(date?: MaybeDate): Date
date
MaybeDate
default:"undefined"
The date value to resolve. If undefined, returns today’s date
Returns a normalized UTC Date object. Handles:
  • ISO date strings (e.g., “2024-01-15”)
  • Unix timestamps
  • Date objects
  • Numeric strings
Example:
import { toResolvedDate } from 'app-datepicker/helpers/to-resolved-date.js';

const date1 = toResolvedDate('2024-01-15');
const date2 = toResolvedDate(1705276800000);
const date3 = toResolvedDate(); // Today's date

toDateString

Converts a Date object to ISO date string format (YYYY-MM-DD).
function toDateString(date: Date): string
date
Date
required
The date to convert to string
Returns ISO date string in YYYY-MM-DD format. Example:
import { toDateString } from 'app-datepicker/helpers/to-date-string.js';

const dateStr = toDateString(new Date('2024-01-15T12:00:00Z'));
console.log(dateStr); // "2024-01-15"

Date Calculations

toDayDiffInclusive

Calculates the number of days between two dates (inclusive).
function toDayDiffInclusive(min: Date | number, max: Date | number): number
min
Date | number
required
Start date (Date object or timestamp)
max
Date | number
required
End date (Date object or timestamp)
Returns the number of days in the range (inclusive). Minimum return value is 1. Example:
import { toDayDiffInclusive } from 'app-datepicker/helpers/to-day-diff-inclusive.js';

const start = new Date('2024-01-01');
const end = new Date('2024-01-10');
const days = toDayDiffInclusive(start, end);
console.log(days); // 10

isInCurrentMonth

Checks if a target date is in the same month and year as a source date.
function isInCurrentMonth(targetDate: Date, sourceDate: Date): boolean
targetDate
Date
required
The date to check
sourceDate
Date
required
The reference date
Example:
import { isInCurrentMonth } from 'app-datepicker/helpers/is-in-current-month.js';

const target = new Date('2024-01-15');
const reference = new Date('2024-01-20');
console.log(isInCurrentMonth(target, reference)); // true

const different = new Date('2024-02-15');
console.log(isInCurrentMonth(different, reference)); // false

Formatting and Internationalization

toFormatters

Creates a complete set of internationalized date formatters for a given locale.
function toFormatters(locale: string): Formatters
locale
string
required
BCP 47 language tag (e.g., “en-US”, “fr-FR”)
locale
string
The locale string
dateFormat
DateTimeFormatter
Formats dates with weekday, month, and day (e.g., “Mon, Jan 15”)
dayFormat
DateTimeFormatter
Formats day numbers (e.g., “15”)
fullDateFormat
DateTimeFormatter
Formats complete dates (e.g., “Jan 15, 2024”)
longMonthFormat
DateTimeFormatter
Formats full month names (e.g., “January”)
longMonthYearFormat
DateTimeFormatter
Formats month and year (e.g., “January 2024”)
longWeekdayFormat
DateTimeFormatter
Formats full weekday names (e.g., “Monday”)
narrowWeekdayFormat
DateTimeFormatter
Formats single-letter weekdays (e.g., “M”)
yearFormat
DateTimeFormatter
Formats years (e.g., “2024”)
Example:
import { toFormatters } from 'app-datepicker/helpers/to-formatters.js';

const formatters = toFormatters('en-US');
const date = new Date('2024-01-15');

console.log(formatters.fullDateFormat(date)); // "Jan 15, 2024"
console.log(formatters.longMonthFormat(date)); // "January"
console.log(formatters.longWeekdayFormat(date)); // "Monday"

Calendar Generation

toMultiCalendars

Generates calendar data for multiple months with proper date validation.
function toMultiCalendars(options: ToMultiCalendarsInit): MultiCalendars
options
ToMultiCalendarsInit
required
Configuration object for calendar generation
options.currentDate
Date
required
The focal date for calendar generation
options.locale
string
required
BCP 47 language tag
options.dayFormat
DateTimeFormatter
required
Formatter for day numbers
options.fullDateFormat
DateTimeFormatter
required
Formatter for full dates
options.longWeekdayFormat
DateTimeFormatter
required
Formatter for weekday names
options.narrowWeekdayFormat
DateTimeFormatter
required
Formatter for narrow weekday labels
options.count
number
Number of months to generate (defaults to 1, always becomes odd number)
options.min
Date
Minimum selectable date
options.max
Date
Maximum selectable date
options.disabledDates
string
Comma-separated list of disabled dates
options.disabledDays
string
Comma-separated list of disabled weekdays (0-6)
options.firstDayOfWeek
number
First day of week (0 = Sunday, 1 = Monday, etc.)
options.showWeekNumber
boolean
Whether to show week numbers
options.weekLabel
string
Label for week number column
options.weekNumberType
WeekNumberType
Type of week numbering system
calendars
Array<Calendar>
Array of calendar objects for each month
weekdays
CalendarWeekday[]
Weekday header information
disabledDatesSet
Set<number>
Set of disabled date timestamps
disabledDaysSet
Set<number>
Set of disabled weekday numbers
key
string
Unique key for the calendar configuration

toNextSelectableDate

Finds the next selectable date from a given date, respecting constraints.
function toNextSelectableDate(init: ToNextSelectableDateInit): Date
init.date
Date
required
Starting date
init.key
SupportedKey
required
Navigation key pressed (e.g., ArrowRight, ArrowDown)
init.minTime
number
required
Minimum timestamp allowed
init.maxTime
number
required
Maximum timestamp allowed
init.disabledDatesSet
Set<number>
required
Set of disabled date timestamps
init.disabledDaysSet
Set<number>
required
Set of disabled weekday numbers
Returns the next selectable date in the navigation direction.

List Generation

toYearList

Generates an array of years between min and max dates.
function toYearList(min: Date, max: Date): number[]
min
Date
required
Minimum date
max
Date
required
Maximum date
Returns array of years from min to max (inclusive). Example:
import { toYearList } from 'app-datepicker/helpers/to-year-list.js';

const years = toYearList(
  new Date('2020-01-01'),
  new Date('2024-12-31')
);
console.log(years); // [2020, 2021, 2022, 2023, 2024]

String Utilities

splitString

Splits a string and optionally transforms each element.
function splitString<ReturnType = string>(
  source: string,
  splitFunction?: SplitStringCallbackFn<ReturnType>,
  separator: RegExp | string = /,\s*/
): ReturnType[]
source
string
required
String to split
splitFunction
SplitStringCallbackFn<ReturnType>
Optional transformation function for each element
separator
RegExp | string
default:"/,\\s*/"
Separator pattern (comma with optional space by default)
Example:
import { splitString } from 'app-datepicker/helpers/split-string.js';

// Simple split
const dates = splitString('2024-01-01, 2024-01-15, 2024-02-01');
console.log(dates); // ['2024-01-01', '2024-01-15', '2024-02-01']

// With transformation
const timestamps = splitString(
  '2024-01-01, 2024-01-15',
  (dateStr) => new Date(dateStr).getTime()
);

Utility Functions

clampValue

Clamps a value between minimum and maximum bounds.
function clampValue(min: number, max: number, value: number): number
min
number
required
Minimum value
max
number
required
Maximum value
value
number
required
Value to clamp
Example:
import { clampValue } from 'app-datepicker/helpers/clamp-value.js';

console.log(clampValue(0, 100, 150)); // 100
console.log(clampValue(0, 100, -10)); // 0
console.log(clampValue(0, 100, 50)); // 50

focusElement

Focuses an element after resolving a promise.
async function focusElement<T extends HTMLElement | null>(
  asyncSelector: Promise<T>,
  thenCallback?: (element: NonNullable<T>) => Promise<void> | void
): Promise<T>
asyncSelector
Promise<T>
required
Promise that resolves to an HTML element
thenCallback
function
Optional callback to execute after focusing
Example:
import { focusElement } from 'app-datepicker/helpers/focus-element.js';

await focusElement(
  Promise.resolve(document.querySelector('.date-button')),
  (element) => {
    element.scrollIntoView({ block: 'nearest' });
  }
);

toClosestTarget

Finds the closest ancestor element matching a selector from an event.
function toClosestTarget<Target extends HTMLElement, TargetEvent extends Event = Event>(
  event: TargetEvent,
  selector: string
): Target | undefined
event
Event
required
The event object
selector
string
required
CSS selector to match
Example:
import { toClosestTarget } from 'app-datepicker/helpers/to-closest-target.js';

element.addEventListener('click', (event) => {
  const button = toClosestTarget<HTMLButtonElement>(event, 'button[data-date]');
  if (button) {
    console.log(button.dataset.date);
  }
});

nullishAttributeConverter

Attribute converter that converts falsy values to undefined for Lit elements.
const nullishAttributeConverter: ComplexAttributeConverter['toAttribute']
Example:
import { nullishAttributeConverter } from 'app-datepicker/helpers/nullish-attribute-converter.js';
import { LitElement, html } from 'lit';
import { property } from 'lit/decorators.js';

class MyElement extends LitElement {
  @property({ converter: { toAttribute: nullishAttributeConverter } })
  max?: string;
}

Import Paths

All helper functions can be imported from their individual modules:
import { dateValidator } from 'app-datepicker/helpers/date-validator.js';
import { toFormatters } from 'app-datepicker/helpers/to-formatters.js';
import { toMultiCalendars } from 'app-datepicker/helpers/to-multi-calendars.js';
// ... etc
For TypeScript projects, corresponding type definitions are available:
import type { DateValidatorResult, MaybeDate, MultiCalendars } from 'app-datepicker/helpers/typings.js';