Dates
Sugar makes working with dates easy, and has support for multiple languages.
Setup
Basic
Advanced
Installing
Sugar is a library that provides many methods for different native types.
A dates-only build can be created at the download
page, or using the npm module sugar-date
.
Usage
Sugar methods have three different modes of use: Default, Chainable, and Extended.
Static and chainable methods go through the Sugar
global object, while extended
mode maps methods directly to native prototypes. For more information about what
this means and which mode to use, see the Getting Started guide.
Parsing
Creating dates in Sugar is handled through the create
method. It accepts strings
and numbers, as well as other date objects. Date parsing of strings happens automatically,
and will use the current locale (English by default) if none is specified. Locale codes
can be passed as the second argument.
Sugar supports a wide variety of formats in many different locales. Custom formats can also be added if necessary. For more, see Date Parsing. The box below is a sample of a variety of different English formats that Sugar understands. Click on the links or use the text input:
- now
- today
- next week
- last year
- the 15th
- next Tuesday
- 3pm Wednesday
- in 30 minutes
- in half a year
- five years ago
- yesterday at 4pm
- half an hour ago
- an hour from now
- 6:30pm in three days
- the 4th of July
- next week Thursday
- the end of February
- two weeks from today
- the end of next week
- next Saturday at 10am
- the first day of 2013
- four days after Monday
- March 15th of last year
- two days after tomorrow
- the last day of February
- Sunday, January 15th 2012
- the beginning of this month
- the 2nd Tuesday of November
- 5-2002
- 8/25/1978
- 8-25-1978
- 8.25.1978
- 2012-12-31
- 2016-Mar-18
- 22 August
- April 2012
- June 3rd, 2005
- 1 Dec. 2016
- 17760523T024508+0830
- 1997-07-16T19:20:30+01:00
- 08-25-1978 11:42:32.488am
- Wed, 03 Jul 2008 08:00:00 EST
Manipulating
Dates can easily be manipulated and shifted using the methods set
, advance
,
and rewind
. In addition to accepting different forms of input, these methods
also optionally can reset units lower than the most specific unit being set.
reset
will also reset any unit and lower (time is reset by default). Finally
the unit add
methods are useful for focusing on a single unit.
The following methods all modify the date:
Name | Description |
---|---|
set | Sets multiple date units. Can optionally reset the date. |
advance | Shifts the date forward. Can optionally reset the date. |
rewind | Shifts the date backward Can optionally reset the date. |
reset | Resets any date unit and lower units (time is reset by default). |
addYears | Adds n years to the date. |
addMonths | Adds n months to the date. |
addWeeks | Adds n weeks (7 days) to the date. |
addDays | Adds n days to the date. |
addHours | Adds n hours to the date. |
addMinutes | Adds n minutes to the date. |
addSeconds | Adds n seconds to the date. |
addMilliseconds | Adds n milliseconds to the date. |
beginningOfDay | Moves the date to the beginning of the day. |
beginningOfWeek | Moves the date to the beginning of the week as defined by the current or passed locale. |
beginningOfISOWeek | Moves the date to the Monday of this week (ISO8601). |
beginningOfMonth | Moves the date to the beginning of the month. |
beginningOfYear | Moves the date to the beginning of the year. |
endOfDay | Moves the date to the end of the day. |
endOfWeek | Moves the date to the end of the week as defined by the current or passed locale. |
endOfISOWeek | Moves the date to the end of Sunday of this week (ISO8601). |
endOfMonth | Moves the date to the end of the month. |
endOfYear | Moves the date to the end of the year. |
setWeekday | Alias for setDay . |
setISOWeek | Sets the ISO week number (of the year) as defined by ISO8601. |
Comparing
Sugar adds methods beginning with the is
prefix that allow dates
to be compared or tested against different criteria. The is
method itself will directly compare dates with a margin of error. When
passed a string, it will also intelligently use the precision implied in the
input. For example, passing "Oct 21st 2015"
will match anything that falls
within the entire day, however passing new Date(2015, 9, 21)
will match only
that exact moment (with an optional margin for error).
Full list of date comparison methods:
Name | Notes |
---|---|
is | Directly compares the first argument, implying precision when using a string format. |
isAfter | True if the date falls after the first argument. |
isBefore | True if the date falls before the first argument. |
isBetween | True if the date falls between the first two arguments. |
isLastWeek | Locale dependent. |
isThisWeek | Locale dependent. |
isNextWeek | Locale dependent. |
isLastMonth | |
isThisMonth | |
isNextMonth | |
isLastYear | |
isThisYear | |
isNextYear | |
isLeapYear | |
isToday | |
isYesterday | |
isTomorrow | |
isSunday | |
isMonday | |
isTuesday | |
isWednesday | |
isThursday | |
isFriday | |
isSaturday | |
isFuture | |
isPast | |
isWeekday | True if the date is either Saturday or Sunday. |
isWeekend | True if the date is Monday-Friday. |
isValid | True if the date does not have an internal value of NaN . |
Unit Operations
Performing a subtract operation -
on two dates will give the relative distance
between them in milliseconds, but this is often required to be in a different
unit. Sugar provides the methods unitsSince
, unitsAgo
, unitsUntil
, and
unitsFromNow
to return time differences in any unit required.
Full list of methods:
Name |
---|
millisecondsSince |
secondsSince |
minutesSince |
hoursSince |
daysSince |
weeksSince |
monthsSince |
yearsSince |
millisecondsAgo |
secondsAgo |
minutesAgo |
hoursAgo |
daysAgo |
weeksAgo |
monthsAgo |
yearsAgo |
millisecondsUntil |
secondsUntil |
minutesUntil |
hoursUntil |
daysUntil |
weeksUntil |
monthsUntil |
yearsUntil |
millisecondsFromNow |
secondsFromNow |
minutesFromNow |
hoursFromNow |
daysFromNow |
weeksFromNow |
monthsFromNow |
yearsFromNow |
Formatting
Sugar allows multiple ways to convert dates to a string in different formats. The format
method supports two types of tokens: LDML,
which are more intuitive and easy to remember, as well as strftime,
which are found in a variety of programming languages. In addition to allowing
output in a user defined format, four preset format types also exist: short
,
medium
, long
, and full
. The short format presents only the date in a numeric
format. Medium uses a longer, word-based format. Long adds the time to this format.
Full adds to this the weekday. The major advantage to these formats is that they
exist on all locales and can be quickly used without knowing the details of date
formatting in those languages.
Finally, relative date strings can also be output using the methods relative
and relativeTo
. These methods will automatically choose the appropriate unit,
for example minutes
for a date less than an hour ago.
Full list of formatting methods:
Name | Description |
---|---|
format | Outputs the date in a user specified format. Uses LDML or STRF tokens. |
short | Outputs the date in the short format. |
medium | Outputs the date in the medium format. |
long | Outputs the date in the long format. |
full | Outputs the date in the full format. |
relative | Outputs a string in units relative to the current date ("ago" or "from now"). |
relativeTo | Outputs a string in units relative to another date. |
strftime tokens
Token | Value |
---|---|
%a |
Abbreviated day of the week (Sun) |
%A |
Full day of the week (Sunday) |
%b |
Abbreviated month name (Jan) |
%B |
Full month name (January) |
%c |
Common timestamp format (Thu Aug 5 2010 2:03 PM) |
%C |
Century as 2 digit string (20) |
%d |
2-digit day of the month with 0 ("05") |
%D |
American month first slash format (08/05/12) |
%e |
2-digit day of the month with space (" 5") |
%F |
Common datestamp format (2010-08-05) |
%g |
ISO8601 week year (2 digits) |
%G |
ISO8601 week year (4 digits) |
%h |
Abbreviated month name (Jan) |
%H |
2-digit hours in 24-hour format (13) |
%I |
2-digit hours in 12-hour format (01) |
%j |
Day of the year (365) |
%m |
2-digit month |
%M |
2-digit minutes |
%p |
AM/PM (uppercase) |
%P |
am/pm (lowercase) |
%r |
12 hour clock time with seconds (02:03:02 PM) |
%R |
24 hour clock time without seconds (14:03) |
%S |
2-digit seconds |
%T |
24 hour clock time without seconds (14:03:02) |
%u |
ISO8601 day of the week (Sunday = 7) |
%U |
2-digit week number (First Sunday of year = 01, prev = 00) |
%V |
2-digit ISO-8601 week number. First week of the year has at least 4 weekdays, Monday is the start of the week |
%w |
Day of the week (Sunday = 0) |
%W |
2-digit numeric week of the year. First Monday is the first week |
%x |
Locale based representation of the date (ex. 08/05/2010) |
%X |
Locale based representation of the time (ex. 2:03 PM) |
%Y |
4-digit year |
LDML tokens
Token | Value |
---|---|
{ms} |
Milliseconds |
{S} |
Milliseconds |
{SSS} |
3-digit milliseconds |
{s} |
Seconds |
{ss} |
2-digit seconds |
{seconds} |
Seconds |
{minutes} |
Minutes |
{m} |
Minutes |
{mm} |
2-digit minutes |
{hours} |
Hours (12 hour clock) |
{h} |
Hours (12 hour clock) |
{hh} |
2-digit hours (12 hour clock) |
{hours} |
Hours (12 hour clock) |
{H} |
Hours (24 hour clock) |
{HH} |
2-digit hours (24 hour clock) |
{date} |
Date |
{d} |
Date |
{dd} |
2-digit date |
{do} |
Ordinal date (5th) |
{dow} |
Lowercase abbreviated day of the week (sun) |
{Dow} |
Abbreviated day of the week (Sun) |
{e} |
Numeric day of the week (1) |
{eo} |
Ordinal numeric day of the week (1st) |
{weekday} |
Lowercase day of the week (sunday) |
{Weekday} |
Day of the week (Sunday) |
{D} |
Day of the year (365) |
{DDD} |
3-digit day of the year (365) |
{full} |
A full format specific to the locale |
{gg} |
2-digit week year |
{gggg} |
4-digit week year |
{GG} |
2-digit ISO8601 week year |
{GGGG} |
4-digit ISO8601 week year |
{long} |
A long format specific to the locale |
{M} |
Numeric month |
{MM} |
2-digit numeric month |
{medium} |
A medium format specific to the locale |
{month} |
Lowercase month name (january) |
{Month} |
Month name (January) |
{mon} |
Lowercase abbreviated month name (jan) |
{Mon} |
Abbreviated month name (Jan) |
{Mo} |
Ordinal month (1st) |
{yy} |
2-digit year (10) |
{yyyy} |
4-digit year (2010) |
{year} |
4-digit year (2010) |
{Q} |
Quarter |
{short} |
A short format specific to the locale |
{stamp} |
A timestamp format specific to the locale |
{t} |
AM/PM as 1 lowercase letter (a/p) |
{T} |
AM/PM as 1 uppercase letter (A/P) |
{tt} |
am/pm |
{TT} |
AM/PM |
{time} |
Time string specific to the locale |
{w} |
Locale based week number |
{ww} |
2-digit locale based week number |
{wo} |
Ordinal locale based week number |
{W} |
ISO8601 week number |
{WW} |
2-digit ISO8601 week number |
{Wo} |
Ordinal ISO8601 week number |
{X} |
Unix timestamp (seconds) |
{x} |
Unix timestamp (milliseconds) |
{Z} |
Timezone offset with colon (+09:00) |
{ZZ} |
Timezone offset without colon (+0900) |
Numbers
The Sugar date module also defines a number of useful methods on numbers, as well.
The most handy are the unit shortcuts, which take the number as a unit of time and
convert them to milliseconds. Numbers also have the methods unitsBefore
, unitsAgo
,
unitsAfter
, and unitsFromNow
as shortcuts. Note that these unit methods can also
be called in their singular form.
Finally, the duration
method will return a string similar to relative
, taking
the number as millseconds and converting to the unit most appropriate.
Full list of methods mapped to numbers:
Name | Notes |
---|---|
duration | Takes the number as milliseconds and returns a localized string. |
milliseconds | |
seconds | |
minutes | |
hours | |
days | |
weeks | |
months | Ambiguous as a unit. Considered here to be 30.4375 days. |
years | |
millisecondsBefore | |
secondsBefore | |
minutesBefore | |
hoursBefore | |
daysBefore | |
weeksBefore | |
monthsBefore | If the date falls on a day that doesn't exist, it will be shifted into the previous month. |
yearsBefore | |
millisecondsAfter | |
secondsAfter | |
minutesAfter | |
hoursAfter | |
daysAfter | |
weeksAfter | |
monthsAfter | If the date falls on a day that doesn't exist, it will be shifted into the previous month. |
yearsAfter | |
millisecondsAgo | |
secondsAgo | |
minutesAgo | |
hoursAgo | |
daysAgo | |
weeksAgo | |
monthsAgo | If the date falls on a day that doesn't exist, it will be shifted into the previous month. |
yearsAgo | |
millisecondsFromNow | |
secondsFromNow | |
minutesFromNow | |
hoursFromNow | |
daysFromNow | |
weeksFromNow | |
monthsFromNow | If the date falls on a day that doesn't exist, it will be shifted into the previous month. |
yearsFromNow |
Locales
Sugar supports 17 major locales. These can be added separately or included in
the build via the downloads page. Locales contain various information
including parsing and output of both static and relative formats. Once included,
locales can either be set globally via the setLocale
method, or passed as a code
to methods such as isLastWeek
which are locale dependent. Additionally, any method
such as create
that accepts an options object will accept a locale code in its place.
Locale related methods:
Name | Notes |
---|---|
getLocale | Returns the locale for the first argument or the current locale if none is passed. |
getAllLocales | Returns all locales as an array of objects. |
getAllLocaleCodes | Returns all locale codes as an array of strings. |
setLocale | Sets the current locale. |
addLocale | Allows new locales to be defined. |
removeLocale | Removes a locale from the list of known locales. |
Timezones
As many developers know, Javascript does not natively provide support for handling timezones (all Javascript dates are local to their environment). Handling this properly is complex, and falls outside the scope of Sugar. However, special options are included that allows Sugar to play nicely with other libraries designed for this purpose. Specifically, the newDateInternal option allows dates created internally by Sugar to be transformed to simulate being in a different timezone.
UTC Time
Although Sugar does not handle timezones directly, it does provide a few methods
that make working with dates intended to be in UTC easier. First, methods such as
create
that allow an options object will accept an option fromUTC
that indicates
that the incoming string is in UTC time. This is most useful when reading in dates
from a server, which are often standardized to UTC time.
Additionally, the method setUTC
(which also exists as an option of the same name)
will set an internal flag on a date telling Sugar to use UTC-based methods such as
getUTCHours
internally when handling the date. This can be useful if dates need
to be output as UTC. Note that native methods like getHours
still return local values.
List of UTC related methods:
Name | Description |
---|---|
isUTC | Returns true if the date has no timezone offset. |
setUTC | Sets a flag on the date telling it to use UTC methods internally. |
getUTCOffset | Returns a string representation of the offset (+0900, etc). |
getUTCWeekday | Alias for native getUTCDay. |
ISO-8601
Sugar natively supports ISO-8601 as one of its core formats. Most modern browsers
can also parse this format, however inconsistencies exist with dates that don't
specify a timezone offset (either Z
or +-hh:mm
). To ensure compatibility,
dates such as server timestamps should always supply an offset. If they do not,
Sugar will correctly parse these formats as local time (as per ISO-8601), however
be aware that this may differ from native parsing (new Date). If UTC time is required,
fromUTC
will force the date to be parsed as UTC time, and should be used.
Ranges
The Sugar range module provides a lightweight, conventient way to handle a date range that has a distinct start and end. Date ranges can be compared, combined, and iterated over.
The date range is created through the Date.range
method, passing a start and
end value. These values may be strings, which will be forwarded to the create
method, numbers for timestamps, or date objects. The date range constructor also
accepts a single string in the forms:
Format |
---|
START to END |
from START until END |
DATE from START until END |
DATE for DURATION |
for DURATION on DATE |
for DURATION starting DATE |
for DURATION starting at TIME |
DATE at TIME for DURATION |
Range methods appear in the API reference and can be included or excluded in custom builds, however they differ from standard Sugar methods in that they are always called as instance methods on range objects, and never as static methods.