DateHelper

A static class offering date manipulation, comparison, parsing and formatting helper methods.

Parsing strings

Use DateHelper.parse() to parse strings into dates. It accepts a date string and a format specifier. The format specifier is string built up using the following tokens:

Unit Token Description
Year YYYY 4-digits year, like: 2018
Y numeric, any number of digits
YY < 68 -> 2000, > 68 -> 1900
Month MM 01 - 12
Month MMM Short name of the month
Date DD 01 - 31
Hour HH 00 - 23 or 1 - 12
Minute mm 00 - 59
Second ss 00 - 59
Millisecond S 0 - 9 [000, 100, 200 .. 900 ]
SS 00 - 99 [000, 010, 020 .. 990 ]
SSS 000 - 999 [000, 001, 002 .. 999 ]
AM/PM A AM or PM
a am or pm
TimeZone Z Z for UTC or +-HH:mm. Local timezone if left out
Predefined L Long date, MM/DD/YYYY
LT Long time, HH:mm A

Default parse format is: 'YYYY-MM-DDTHH:mm:ss.SSSZ' see defaultParseFormat.

For example:

DateHelper.parse('2018-11-06', 'YYYY-MM-DD');
DateHelper.parse('13:14', 'HH:mm');
DateHelper.parse('6/11/18', 'DD/MM/YY');

Note that date strings without timezone information ('Z' or '+-HH:mm') will be in the local timezone. Eg. '2024-05-14' -> local time, '2024-05-14Z' -> UTC

Formatting dates

Use DateHelper.format() to create a string from a date using a format specifier. The format specifier is similar to that used when parsing strings. It can use the following tokens (input used for output below is new Date(2018,8,9,18,7,8,145)):

Unit Token Description & output
Year YYYY 2018
YY 18
Y 2018
Quarter Q 3
Qo 3rd
Month MMMM September
MMM Sep
MM 09
Mo 9th
M 9
Week (iso) WW 37 (2 digit, zero padded)
Wo 37th
W 37
WWp Week 37 (localized prefix, zero pad)
Wp Week 37 (localized prefix)
WWp0 W37 (localized prefix)
Wp0 W37 (localized prefix)
Date DDDD Day of year, 3 digits
DDDo Day of year, ordinal
DDD Day of year
DD 09
Do 9th
D 9
Weekday dddd Sunday
ddd Sun
dd Su
d1 S
do 0th
d 0
Hour HH 18 (00 - 23)
H 18 (0 - 23)
hh 06 (00 - 12)
h 6 (0 - 12)
KK 19 (01 - 24)
K 19 (1 - 24)
kk 06 or 18, locale determines
k 6 or 18, locale determines
Minute mm 07
m 7
Second ss 08
s 8
Millisecond S 1 (100ms)
SS 14 (140ms)
SSS 145 (145ms)
AM/PM A AM or PM
a am or pm
Predefined LT H: 2-digit (2d), m: 2d
(uses browser locale) LTS H: 2d, m: 2d, s : 2d
LST Depends on 12 or 24 hour clock
12h, H : 1d, m : 0 or 2d
24h, H : 2d, m : 2d
L Y: numeric (n), M : 2d, D : 2d
l Y: n, M : n, D : n
LL Y: n, M : long (l), D : n
ll Y: n, M : short (s), D : n
LLL Y: n, M : l, D : n, H: n, m: 2d
lll Y: n, M : s, D : n, H: n, m: 2d
LLLL Y: n, M : l, D : n, H: n, m: 2d, d: l
llll Y: n, M : s, D : n, H: n, m: 2d, d: s
u YYYYMMDDZ in UTC zone
uu YYYYMMDDTHHMMSSZ in UTC zone

Default format is: 'YYYY-MM-DDTHH:mm:ssZ' see defaultFormat

For example:

DateHelper.format(new Date(2018,10,6), 'YYYY-MM-DD'); // 2018-11-06
DateHelper.format(new Date(2018,10,6), 'M/D/YY'); // 11/6/18

Using embedded text inside format string

Arbitrary text can be embedded in the format string by wrapping it with {}:

DateHelper.format(new Date(2019, 7, 16), '{It is }dddd{, yay!}') -> It is Friday, yay!

Overriding Formatters

To override formatters, you need to configure the locale.

Here is a sample code snippet demonstrating how to override formatters using a custom locale.

const customLocale = {
    DateHelper : {
        formats : {
            ll : date => {
                return DateHelper.format(date, 'DD.MM.YYYY');
            },
            L : date => {
                return DateHelper.format(date, 'DD--MM--YYYY')
            },
            LT : date => {
                return DateHelper.format(date, 'HH-mm');
            },
            LTS : date => {
                return DateHelper.format(date, 'HH-mm-ss');
            }
        }
    }
};

// Extend the English locale with the custom locale
LocaleHelper.publishLocale('En', locale);

Once the custom locale is published, you can use the overridden formatters with DateHelper.format().

DateHelper.format(new Date(2024, 0, 12, 12, 4, 5), 'll') // Output: 12.01.2024
DateHelper.format(new Date(2024, 0, 12, 12, 4, 5), 'L') // Output: 12--01--2024
DateHelper.format(new Date(2024, 0, 12, 12, 4, 5), 'LT') // Output: 12-04
DateHelper.format(new Date(2024, 0, 12, 12, 4, 5), 'LTS') // Output: 12-04-05

Unit names

Many DateHelper functions (for example add, as, set) accepts a unit among their params. The following units are available:

Unit Aliases
millisecond millisecond, milliseconds, ms
second second, seconds, s
minute minute, minutes, m
hour hour, hours, h
day day, days, d
week week, weeks, w
month month, months, mon, mo, M
quarter quarter, quarters, q
year year, years, y
decade decade, decades, dec

For example:

DateHelper.add(date, 2, 'days');
DateHelper.as('hour', 7200, 'seconds');

Properties

6
amIndicator: stringreadonlystatic

Get the local AM indicator string.

defaultFormat: Stringstatic

Get/set the default format used by format() and parse(). Defaults to 'YYYY-MM-DDTHH:mm:ssZ' (~ISO 8601 Date and time, '1962-06-17T09:21:34Z').

defaultParseFormat: Stringstatic

Get/set the default format used by parse(). Defaults to 'YYYY-MM-DDTHH:mm:ss.SSSZ' or defaultFormat (~ISO 8601 Date and time, '1962-06-17T09:21:34.123Z').

nonWorkingDays: Object<Number, Boolean>readonlystatic

Get non-working days as an object where keys are day indices, 0-6 (Sunday-Saturday), and the value is true. This is determined by the current locale's DateHelper.nonWorkingDays parameter.

For example:

{
    0 : true, // Sunday
    6 : true  // Saturday
}
pmIndicator: stringreadonlystatic

Get the local PM indicator string.

weekStartDay: Numberreadonlystatic

Get the first day of week, 0-6 (Sunday-Saturday). This is determined by the current locale's DateHelper.weekStartDay parameter.

Functions

56

Comparison

Checks if this date is >= start and < end.

ParameterTypeDescription
dateDate

The source date

startDate

Start date

endDate

End date

Returns: Boolean -

true if this date falls on or between the given start and end dates

Checks if this date is >= start and <= end.

ParameterTypeDescription
dateDate

The source date

startDate

Start date

endDate

End date

Returns: Boolean -

true if this date falls on or between the given start and end dates

comparestatic

Compares two dates using the specified precision.

ParameterTypeDescription
firstDate

First date

secondDate

Second date

unitString

Unit to calculate difference in. If not given, the comparison will be done up to a millisecond

Returns: Number -

0 = equal, -1 = first before second, 1 = first after second

Compare two units. Returns 1 if first param is a greater unit than second param, -1 if the opposite is true or 0 if they're equal.

ParameterTypeDescription
unit1DurationUnit

The 1st unit

unit2DurationUnit

The 2nd unit

Returns: Number -

Returns 1 if first param is a greater unit than second param, -1 if the opposite is true or 0 if they're equal

Returns true if date ranges intersect.

ParameterTypeDescription
date1StartDate

Start date of first span

date1EndDate

End date of first span

date2StartDate

Start date of second span

date2EndDate

End date of second span

Returns: Boolean -

Returns true if dates intersect

isAfterstatic

Determines if a date succeeds another.

ParameterTypeDescription
firstDate

First date

secondDate

Second date

Returns: Boolean -

true if first succeeds second, otherwise false

isBeforestatic

Determines if a date precedes another.

ParameterTypeDescription
firstDate

First date

secondDate

Second date

Returns: Boolean -

true if first precedes second, otherwise false

isEqualstatic

Checks if two dates are equal.

ParameterTypeDescription
firstDate

First date

secondDate

Second date

unitString

Unit to calculate difference in. If not given, the comparison will be done up to a millisecond

Returns: Boolean -

true if the dates are equal

isStartOfstatic

Checks if date is the start of specified unit.

ParameterTypeDescription
dateDate

Date

unitDurationUnit

Time unit

Returns: Boolean -

true if date is the start of specified unit

isTodaystatic

Determines if a date is today's date.

ParameterTypeDescription
dateDate

The date to check

timeZoneString

The time zone to use for the comparison. If not specified, the local time zone is used:

// Check if a date is today in the local time zone
DateHelper.isToday(new Date());  // true if today
// Check if a date is today in a specific time zone
DateHelper.isToday(new Date(), 'America/New_York');  // true if today in New York
Returns: Boolean -

true if the date is today, otherwise false

Returns true if the first time span completely 'covers' the second time span.

DateHelper.timeSpanContains(
    new Date(2010, 1, 2),
    new Date(2010, 1, 5),
    new Date(2010, 1, 3),
    new Date(2010, 1, 4)
) ==> true
DateHelper.timeSpanContains(
  new Date(2010, 1, 2),
  new Date(2010, 1, 5),
  new Date(2010, 1, 3),
  new Date(2010, 1, 6)
) ==> false
ParameterTypeDescription
spanStartDate

The start date for initial time span

spanEndDate

The end date for initial time span

otherSpanStartDate

The start date for the 2nd time span

otherSpanEndDate

The end date for the 2nd time span

Returns: Boolean -

true if the first time span completely 'covers' the second time span

Manipulate

addstatic

Add days, hours etc. to a date. Always clones the date, original will be left unaffected.

ParameterTypeDescription
dateDate | String

Original date

amountNumber | String | Duration | DurationConfig

Amount of days, hours etc. or a string representation of a duration as accepted by parseDuration or an object with { magnitude, unit } properties

unitDurationUnitShort

Unit for amount

Returns: Date -

New calculated date

clearTimestatic

Removes time from a date (same as calling startOf(date)).

ParameterTypeDescription
dateDate

Date to remove time from

cloneBoolean

Manipulate a copy of the date

Returns: Date -

Manipulated date

clonestatic

Creates a clone of the specified date

ParameterTypeDescription
dateDate

Original date

Returns: Date -

Cloned date

constrainstatic

Constrains the date within a min and a max date.

ParameterTypeDescription
dateDate

The date to constrain

minDate

Min date

maxDate

Max date

Returns: Date -

The constrained date

Copies hours, minutes, seconds, milliseconds from one date to another.

ParameterTypeDescription
targetDateDate

The target date

sourceDateDate

The source date

Returns: Date -

The adjusted target date

diffstatic

Calculates the difference between two dates, in the specified unit.

ParameterTypeDescription
startDate

First date

endDate

Second date

unitDurationUnitShort

Unit to calculate difference in

fractionalBoolean

Specify false to round result

Returns: Number -

Difference in the specified unit

getTimestatic

Returns time with default year, month, and day (Jan 1, 2020).

ParameterTypeDescription
hoursNumber | Date

Hours value or the full date to extract the time of

minutesNumber

Minutes value

secondsNumber

Seconds value

msNumber

Milliseconds value

Returns: Date -

A new default date with the time extracted from the given date or from the time values provided individually

Returns the elapsed milliseconds from the start of the specified date.

ParameterTypeDescription
dateDate

Date to remove date from

unitDurationUnitShort

The time unit to return

Returns: Number -

The elapsed milliseconds from the start of the specified date

setstatic

Sets a part of a date (in place).

ParameterTypeDescription
dateDate

Date to manipulate

unitString | Object

Part of date to set, for example 'minute'. Or an object like { second: 1, minute: 1 }

amountNumber

Value to set

Returns: Date -

Passed date instance modified according to the arguments

startOfstatic

Sets the date to the start of the specified unit, by default returning a clone of the date instead of changing it in place.

ParameterTypeDescription
dateDate

Original date

unitString

Start of this unit, 'day', 'month' etc

cloneBoolean

Manipulate a copy of the date

weekStartDayNumber

The first day of week, 0-6 (Sunday-Saturday). Defaults to the weekStartDay

Returns: Date -

Manipulated date

Other

asMonthsstatic

Converts the passed Date to an accurate number of months passed since the epoch start.

ParameterTypeDescription
timeDate

The Date to find the month value of

Returns: Number -

The number of months since the system time epoch start. May be a fractional value

ceilstatic

Ceils the passed Date value to the nearest increment value.

Optionally may ceil relative to a certain base time point.

For example DH.ceil(new Date('2020-01-01T09:35'), '30 min', new Date('2020-01-01T09:15')) would ceil to 9:45 because that's the closest higher integer number of 30 minute increments from the base.

Note that base is ignored when ceiling to weeks. Use weekStartDay argument which default to the configured weekStartDay dictates what the base of a week is

ParameterTypeDescription
timeDate

The time to ceil

incrementString | Number | DurationConfig | Object

A numeric millisecond value by which to ceil the time or a duration in string form eg '30 min' or object form : {unit: 'minute', magnitude: 30} or {unit: 'minute', increment: 30}

baseDate

The start from which to apply the ceiling

weekStartDayNumber

Will default to what is set in locale

Returns: Date -

New Date instance

clampstatic

Coerces the passed Date between the passed minimum and maximum values.

ParameterTypeDescription
dateDate

The date to clamp between the min and max

minDate

The minimum Date

maxDate

The maximum Date

Returns: Date -

If the passed date is valid, a new Date object which is clamped between the min and max

endOfstatic

Returns the end point of the passed date, that is 00:00:00 of the day after the passed date.

ParameterTypeDescription
dateDate

The date to return the end point of

Returns: Date -

Manipulated date

floorstatic

Floor the passed Date value to the nearest increment value.

Optionally may floor relative to a certain base time point.

For example DH.floor(new Date('2020-01-01T09:35'), '30 min', new Date('2020-01-01T09:15')) would floor to 9:15 because that's the closest lower integer number of 30 minute increments from the base.

Note that base is ignored when flooring to weeks. The configured weekStartDay dictates what the base of a week is.

ParameterTypeDescription
timeDate

The time to floor

incrementString | Number | DurationConfig | Object

A numeric millisecond value by which to floor the time. or a duration in string form eg '30 min' or object form : {unit: 'minute', magnitude: 30} or {unit: 'minute', increment: 30}

baseDate

The start from which to apply the flooring

weekStartDayNumber

Will default to what is set in locale

Returns: Date -

New Date instance

Formats a range of dates using the specified format. Because two dates are involved, the format specifier uses the tokens S{} and E{}. The text contained between the {} is the format for the start date or end date, respectively. Text not inside these tokens is retained verbatim.

For example:

 DateHelper.formatRange(dates, 'S{DD MMM YYYY} - E{DD MMM YYYY}');

The above will format dates[0] based on the S{DD MMM YYYY} segment and dates[1] using E{DD MMM YYYY}. The ' - '` between these will remain between the two formatted dates.

ParameterTypeDescription
datesDate[]

An array of start date and end date ([startDate, endDate])

formatString

The format specifier

Returns: String
getDeltastatic

Converts a millisecond time delta to an object structure. For example 1000 * 60 * 60 * 50 milliseconds the result would be as:

{
    day  : 2,
    hour : 2
}
ParameterTypeDescription
deltaNumber

The millisecond delta value

optionsObject

Formatting options

options.abbrevBoolean

Pass true to use abbreviated unit names, eg { d: 2, h: 2 } for the above example

options.precisionString

The minimum precision unit

options.ignoreLocaleBoolean

Pass true to return unlocalized unit name. Requires abbrev to be false

options.maxUnitString

Name of the maximum unit in the output. e.g. if you pass day then you'll get { h: 25 } instead of { d: 1, h: 1 }

Returns: Object -

The object with the values for each unit

isDatestatic

Checks if value is a date object. Allows to recognize date object even from another context, like the top frame when used in an iframe.

ParameterTypeDescription
value*

Value to check

Returns: Boolean -

true if value is a date object

Checks if date object is valid.

For example:

date = new Date('foo')
date instanceof Date // true
date.toString() // Invalid Date
isNaN(date) // true
DateHelper.isValidDate(date) // false

date = new Date()
date instanceof Date // true
date.toString() // Mon Jan 13 2020 18:27:38 GMT+0300 (GMT+03:00)
isNaN(date) // false
DateHelper.isValidDate(date) // true
ParameterTypeDescription
dateDate

Date

Returns: Boolean -

true if date object is valid

roundstatic

Rounds the passed Date value to the nearest increment value.

Optionally may round relative to a certain base time point.

For example DH.round(new Date('2020-01-01T09:35'), '30 min', new Date('2020-01-01T09:15')) would round to 9:45 because that's the nearest integer number of 30 minute increments from the base.

Note that base is ignored when rounding to weeks. The configured weekStartDay dictates what the base of a week is.

ParameterTypeDescription
timeDate

The time to round

incrementString | Number

A millisecond value by which to round the time May be specified in string form eg: '15 minutes'

baseDate

The start from which to apply the rounding

weekStartDayNumber

Will default to what is set in locale

Returns: Date -

New Date instance

Parse & format

asstatic

Converts the specified amount of one unit (fromUnit) into an amount of another unit (toUnit).

ParameterTypeDescription
toUnitString

The name of units to convert to, eg: 'ms'

amountNumber | String

The time to convert. Either the magnitude number form or a duration string such as '2d'

fromUnitString

If the amount was passed as a number, the units to use to convert from

Returns: Number

Converts the specified amount of desired unit into milliseconds. Can be called by only specifying a unit as the first argument, it then uses amount = 1.

For example:

asMilliseconds('hour') == asMilliseconds(1, 'hour')
ParameterTypeDescription
amountNumber | String

Amount, what of is decided by specifying unit (also takes a unit which implies an amount of 1)

unitString

Time unit (s, hour, months etc.)

Returns: Number
createstatic

Creates a date from a date definition object. The object can have the following properties:

  • year
  • month
  • date (day in month)
  • hours
  • minutes
  • seconds
  • milliseconds
  • amPm : 'am' or 'pm', implies 12-hour clock
  • timeZone : offset from UTC in minutes
ParameterTypeDescription
definitionObject
definition.yearNumber
definition.monthNumber
definition.dateNumber
definition.hoursNumber
definition.minutesNumber
definition.secondsNumber
definition.millisecondsNumber
definition.amPmNumber
definition.timeZoneNumber
Returns: Date -

new Date instance

formatstatic

Converts a date to string with the specified format. Formats heavily inspired by https://momentjs.com. Available formats (input used for output below is new Date(2018,8,9,18,7,8,145)):

Unit Token Description & output
Decade DC 2010s
Year YYYY 2018
YY 18
Y 2018
Quarter Q 3
Qo 3rd
Month MMMM September
MMM Sep
MM 09
Mo 9th
M 9
Week (iso) WW 37 (2 digit, zero padded)
Wo 37th
W 37
WWp Week 37 (localized prefix, zero pad)
Wp Week 37 (localized prefix)
WWp0 W37 (localized prefix)
Wp0 W37 (localized prefix)
Date DDDD Day of year, 3 digits
DDDo Day of year, ordinal
DDD Day of year
DD 09
Do 9th
D 9
Weekday dddd Sunday
ddd Sun
dd Su
d1 S
do 0th
d 0
Hour HH 18 (00 - 23)
H 18 (0 - 23)
hh 06 (00 - 12)
h 6 (0 - 12)
KK 19 (01 - 24)
K 19 (1 - 24)
kk 06 or 18, locale determines
k 6 or 18, locale determines
Minute mm 07
m 7
Second ss 08
s 8
Millisecond S 1 (100ms)
SS 14 (140ms)
SSS 145 (145ms)
AM/PM A AM or PM
a am or pm
Predefined LT H: 2-digit (2d), m: 2d
(uses browser locale) LTS H: 2d, m: 2d, s : 2d
LST Depends on 12 or 24 hour clock
12h, H : 1d, m : 0 or 2d
24h, H : 2d, m : 2d
L Y: numeric (n), M : 2d, D : 2d
l Y: n, M : n, D : n
LL Y: n, M : long (l), D : n
ll Y: n, M : short (s), D : n
LLL Y: n, M : l, D : n, H: n, m: 2d
lll Y: n, M : s, D : n, H: n, m: 2d
LLLL Y: n, M : l, D : n, H: n, m: 2d, d: l
llll Y: n, M : s, D : n, H: n, m: 2d, d: s

Some examples:

DateHelper.format(new Date(2019, 7, 16), 'dddd') -> Friday
DateHelper.format(new Date(2019, 7, 16, 14, 27), 'HH:mm') --> 14:27
DateHelper.format(new Date(2019, 7, 16, 14, 27), 'L HH') --> 2019-07-16 14

Using embedded text inside format string

Arbitrary text can be embedded in the format string by wrapping it with {}:

DateHelper.format(new Date(2019, 7, 16), '{It is }dddd{, yay!}') -> It is Friday, yay!
ParameterTypeDescription
dateDate

Date

formatString | function

Desired format (uses defaultFormat if left out), or a function which accepts a Date and returns the required formatted string.

format.dateDate
Returns: String -

Formatted string

Converts a millisecond time delta to a human-readable form. For example 1000 * 60 * 60 * 50 milliseconds would be rendered as '2 days, 2 hours'.

ParameterTypeDescription
deltaNumber

The millisecond delta value

optionsObject

Formatting options

options.abbrevBoolean

Pass true to use abbreviated unit names, eg. '2d, 2h' for the above example

options.precisionString

The minimum precision unit

options.separatorString

The separator to use between magnitude and unit

options.unitSeparatorString

The separator to use between each duration part, defaults to ", " eg. '2d, 2h'

options.asStringBoolean

Pass false to return the result as an array, eg ['2d', '2h'] for the above example

Returns: String -

Formatted string

Returns true for 24-hour format.

ParameterTypeDescription
formatString

Date format

Returns: Boolean -

true for 24-hour format

parsestatic

Returns a date created from the supplied string using the specified format. Will try to create even if format is left out, by first using the default format (see defaultFormat, by default YYYY-MM-DDTHH:mm:ssZ) and then using new Date(dateString). Supported tokens:

Unit Token Description
Year YYYY 4-digits year, like: 2018
Y numeric, any number of digits
YY < 68 -> 2000, > 68 -> 1900
Month MM 01 - 12
Month MMM Short name of the month
Date DD 01 - 31
Hour HH 00 - 23 or 1 - 12
Minute mm 00 - 59
Second ss 00 - 59
Millisecond S 0 - 9 [000, 100, 200 .. 900 ]
SS 00 - 99 [000, 010, 020 .. 990 ]
SSS 000 - 999 [000, 001, 002 .. 999 ]
AM/PM A AM or PM
a am or pm
TimeZone Z Z for UTC or +-HH:mm. Local timezone if left out
Predefined L Long date, MM/DD/YYYY
LT Long time, HH:mm A

Predefined formats and functions used to parse tokens can be localized, see for example the swedish locale SvSE.js.

NOTE: If no date parameters are provided then Jan 01 2020 is used as a default date.

Note that date strings without timezone information ('Z' or '+-HH:mm') will be in the local timezone. Eg. '2024-05-14' -> local time, '2024-05-14Z' -> UTC

ParameterTypeDescription
dateStringString

Date string

formatString

Date format (or defaultParseFormat if left out)

Returns: Date -

new Date instance parsed from the string

Parses a typed duration value according to locale rules.

The value is taken to be a string consisting of the numeric magnitude and the units:

  • The numeric magnitude can be either an integer or a float value. Both ',' and '.' are valid decimal separators.
  • The units may be a recognised unit abbreviation of this locale or the full local unit name.

For example: '2d', '2 d', '2 day', '2 days' will be turned into { magnitude : 2, unit : 'day' } '2.5d', '2,5 d', '2.5 day', '2,5 days' will be turned into { magnitude : 2.5, unit : 'day' }

NOTE: Doesn't work with complex values like '2 days, 2 hours'

ParameterTypeDescription
valueString

The value to parse

allowDecimalsBoolean

Decimals are allowed in the magnitude

defaultUnitDurationUnit | String

Default unit to use if only magnitude passed

Returns: DurationConfig -

If successfully parsed, the result contains two properties, magnitude being a number, and unit being the canonical unit name, NOT a localized name. If parsing was unsuccessful, null is returned

Parses a typed unit name, for example 'ms' or 'hr' or 'yr' into the canonical form of the unit name which may be passed to add or diff.

ParameterTypeDescription
unitNameDurationUnit | DurationUnitShort | String

Time unit name

Query

Get number of days in the current month for the supplied date.

ParameterTypeDescription
dateDate

Date which month should be checked

Returns: Number -

Days in month

getstatic

Get the specified part of a date.

ParameterTypeDescription
dateDate
unitDurationUnit

Part of date, hour, minute etc.

Returns: Number -

The requested part of the specified date

Get the end of previous day.

ParameterTypeDescription
dateDate

Date

noNeedToClearTimeBoolean

Flag to not clear time from the result

Returns: Date -

New Date instance

Get the first date of the month for the supplied date.

ParameterTypeDescription
dateDate

Date

Returns: Date -

New Date instance

Get the last date of the month for the supplied date.

ParameterTypeDescription
dateDate

Date

Returns: Date -

New Date instance

getNextstatic

Get an incremented date. Incrementation based on specified unit and optional amount.

ParameterTypeDescription
dateDate

Date

unitDurationUnit

Time unit

incrementNumber

Increment amount

weekStartDayNumber

Will default to what is set in locale

Returns: Date -

New Date instance

Get the start of the next day.

ParameterTypeDescription
dateDate

Date

cloneBoolean

Clone date

noNeedToClearTimeBoolean

Flag to not clear time from the result

Returns: Date -

Passed Date or new Date instance, depending on the clone flag

Get week number for the date.

ParameterTypeDescription
dateDate

The date

weekStartDayNumber

The first day of week, 0-6 (Sunday-Saturday). Defaults to the weekStartDay

Returns: Number[] -

year and week number

maxstatic

Get the latest of two dates.

ParameterTypeDescription
firstDate

First date

secondDate

Second date

Returns: Date -

Latest date

minstatic

Get the earliest of two dates.

ParameterTypeDescription
firstDate

First date

secondDate

Second date

Returns: Date -

Earliest date

Unit helpers

Turns (10, 'day') into '10 days' etc.

ParameterTypeDescription
countNumber

Amount of unit

unitDurationUnit

Unit, will be normalized (days, d -> day etc.)

Returns: String -

Amount formatted to string

Returns a duration of the timeframe in the given unit.

ParameterTypeDescription
startDate

The start date of the timeframe

endDate

The end date of the timeframe

unitDurationUnit

Duration unit

Returns: Number -

The duration in the units

Returns a localized full name of the duration unit.

For example in the EN locale, for 'd' it will return either 'day' or 'days', depending on the plural argument

Preserves casing of first letter.

ParameterTypeDescription
unitDurationUnit

Time unit

pluralBoolean

Whether to return a plural name or singular

Returns: String -

Localized full name of the duration unit

Returns a localized abbreviated form of the name of the duration unit. For example in the EN locale, for 'qrt' it will return 'q'.

ParameterTypeDescription
unitDurationUnit

Duration unit

Returns: String -

Localized abbreviated form of the name of the duration unit

Get the ratio between two units ( year, month -> 1/12 ).

ParameterTypeDescription
baseUnitDurationUnit

Base time unit

unitDurationUnit

Time unit

acceptEstimateBoolean

If true, process negative values of validConversions

Returns: Number -

Ratio

Normalizes a unit for easier usage in conditionals. For example 'year', 'years', 'y' -> 'year'.

ParameterTypeDescription
unitDurationUnit

Time unit

Returns: String -

Normalized unit name

Typedefs

2
DurationUnit: millisecond | second | minute | hour | day | week | month | quarter | year | String

A string defining a duration unit. Valid values are:

  • "millisecond" - Milliseconds
  • "second" - Seconds
  • "minute" - Minutes
  • "hour" - Hours
  • "day" - Days
  • "week" - Weeks
  • "month" - Months
  • "quarter" - Quarters
  • "year"- Years
DurationUnitShort: ms | s | m | h | d | w | M | y | String

A string defining an abbreviated duration unit. Valid values are:

  • "ms" - Milliseconds
  • "s" - Seconds
  • "m" - Minutes
  • "h" - Hours
  • "d" - Days
  • "w" - Weeks
  • "M" - Months
  • "q" - Quarters
  • "y"- Years