date-and-time
This JS library is just a collection of functions for manipulating date and time. It's small, simple, and easy to learn.
Why
Nowadays, JS modules have become larger, more complex, and dependent on many other modules. It is important to strive for simplicity and smallness, especially for modules that are at the bottom of the dependency chain, such as those that handle date and time.
Features
- Minimalist. Approximately 2k. (minified and gzipped)
- Extensible. Plugin system support.
- Multi language support.
- Universal / Isomorphic. Works anywhere.
- TypeScript support.
- Older browser support. Even works on IE6. :)
Install
npm i date-and-time
Recent Changes
-
3.6.0
- In
parseTZ()
, enabled parsing of the missing hour during the transition from standard time to daylight saving time into a Date type. - In
format()
with the z
token, fixed an issue where some short time zone names were incorrect.
-
3.5.0
- Added
addYearsTZ()
, addMonthsTZ()
, and addDaysTZ()
to the timezone
plugin. - Revised the approach to adding time and removed the third parameter from
addHours()
, addMinutes()
, addSeconds()
, and addMilliseconds()
.
-
3.4.1
- Fixed an issue where
formatTZ()
would output 0:00 as 24:00 in 24-hour format in Node.js.
Usage
import date from 'date-and-time';
const date = require('date-and-time');
- ES Modules for the browser:
<script type="module">
import date from '/path/to/date-and-time.es.min.js';
</script>
<script src="/path/to/date-and-time.min.js">
</script>
Note
- If you want to use ES Modules in Node.js without the transpiler, you need to add
"type": "module"
in your package.json
or change your file extension from .js
to .mjs
. - If you are using TypeScript and having trouble building, please ensure that the following settings in the
compilerOptions
of your tsconfig.json
are set to true
.
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
}
}
API
format(dateObj, arg[, utc])
- @param {Date} dateObj - A Date object
- @param {string|Array.<string>} arg - A format string or its compiled object
- @param {boolean} [utc] - Output as UTC
- @returns {string} A formatted string
const now = new Date();
date.format(now, 'YYYY/MM/DD HH:mm:ss');
date.format(now, 'ddd, MMM DD YYYY');
date.format(now, 'hh:mm A [GMT]Z');
date.format(now, 'hh:mm A [GMT]Z', true);
const pattern = date.compile('ddd, MMM DD YYYY');
date.format(now, pattern);
Available tokens and their meanings are as follows:
token | meaning | examples of output |
---|
YYYY | four-digit year | 0999, 2015 |
YY | two-digit year | 99, 01, 15 |
Y | four-digit year without zero-padding | 2, 44, 888, 2015 |
MMMM | month name (long) | January, December |
MMM | month name (short) | Jan, Dec |
MM | month with zero-padding | 01, 12 |
M | month | 1, 12 |
DD | date with zero-padding | 02, 31 |
D | date | 2, 31 |
dddd | day of week (long) | Friday, Sunday |
ddd | day of week (short) | Fri, Sun |
dd | day of week (very short) | Fr, Su |
HH | 24-hour with zero-padding | 23, 08 |
H | 24-hour | 23, 8 |
hh | 12-hour with zero-padding | 11, 08 |
h | 12-hour | 11, 8 |
A | meridiem (uppercase) | AM, PM |
mm | minute with zero-padding | 14, 07 |
m | minute | 14, 7 |
ss | second with zero-padding | 05, 10 |
s | second | 5, 10 |
SSS | millisecond (high accuracy) | 753, 022 |
SS | millisecond (middle accuracy) | 75, 02 |
S | millisecond (low accuracy) | 7, 0 |
Z | time zone offset value | +0100, -0800 |
ZZ | time zone offset value with colon | +01:00, -08:00 |
You can also use the following tokens by importing plugins. See PLUGINS.md for details.
token | meaning | examples of output |
---|
DDD | ordinal notation of date | 1st, 2nd, 3rd |
AA | meridiem (uppercase with ellipsis) | A.M., P.M. |
a | meridiem (lowercase) | am, pm |
aa | meridiem (lowercase with ellipsis) | a.m., p.m. |
z | time zone name abbreviation | PST, EST |
zz | time zone name | Pacific Standard Time |
Parts of the given format string enclosed in square brackets are considered comments and are output as is, regardless of whether they are tokens or not.
date.format(new Date(), 'DD-[MM]-YYYY');
date.format(new Date(), '[DD-[MM]-YYYY]');
Note 2. Output as UTC
This function outputs the date and time in the local time zone of the execution environment by default. If you want to output in UTC, set the UTC option (the third argument) to true. To output in any other time zone, you will need a plugin.
date.format(new Date(), 'hh:mm A [GMT]Z');
date.format(new Date(), 'hh:mm A [GMT]Z', true);
Note 3. More Tokens
You can also define your own tokens. See EXTEND.md for details.
parse(dateString, arg[, utc])
- @param {string} dateString - A date and time string
- @param {string|Array.<string>} arg - A format string or its compiled object
- @param {boolean} [utc] - Input as UTC
- @returns {Date} A Date object
date.parse('2015/01/02 23:14:05', 'YYYY/MM/DD HH:mm:ss');
date.parse('02-01-2015', 'DD-MM-YYYY');
date.parse('11:14:05 PM', 'hh:mm:ss A');
date.parse('11:14:05 PM', 'hh:mm:ss A', true);
date.parse('23:14:05 GMT+0900', 'HH:mm:ss [GMT]Z');
date.parse('Jam 1 2017', 'MMM D YYYY');
date.parse('Feb 29 2017', 'MMM D YYYY');
Available tokens and their meanings are as follows:
token | meaning | examples of acceptable form |
---|
YYYY | four-digit year | 0999, 2015 |
Y | four-digit year without zero-padding | 2, 44, 88, 2015 |
MMMM | month name (long) | January, December |
MMM | month name (short) | Jan, Dec |
MM | month with zero-padding | 01, 12 |
M | month | 1, 12 |
DD | date with zero-padding | 02, 31 |
D | date | 2, 31 |
HH | 24-hour with zero-padding | 23, 08 |
H | 24-hour | 23, 8 |
hh | 12-hour with zero-padding | 11, 08 |
h | 12-hour | 11, 8 |
A | meridiem (uppercase) | AM, PM |
mm | minute with zero-padding | 14, 07 |
m | minute | 14, 7 |
ss | second with zero-padding | 05, 10 |
s | second | 5, 10 |
SSS | millisecond (high accuracy) | 753, 022 |
SS | millisecond (middle accuracy) | 75, 02 |
S | millisecond (low accuracy) | 7, 0 |
Z | time zone offset value | +0100, -0800 |
ZZ | time zone offset value with colon | +01:00, -08:00 |
You can also use the following tokens by importing plugins. See PLUGINS.md for details.
token | meaning | examples of acceptable form |
---|
YY | two-digit year | 90, 00, 08, 19 |
AA | meridiem (uppercase with ellipsis) | A.M., P.M. |
a | meridiem (lowercase) | am, pm |
aa | meridiem (lowercase with ellipsis) | a.m., p.m. |
dddd | day of week (long) | Friday, Sunday |
ddd | day of week (short) | Fri, Sun |
dd | day of week (very short) | Fr, Su |
SSSSSS | microsecond (high accuracy) | 123456, 000001 |
SSSSS | microsecond (middle accuracy) | 12345, 00001 |
SSSS | microsecond (low accuracy) | 1234, 0001 |
Note 1. Invalid Date
If this function fails to parse, it will return Invalid Date
. Notice that the Invalid Date
is a Date object, not NaN
or null
. You can tell whether the Date object is invalid as follows:
const today = date.parse('Jam 1 2017', 'MMM D YYYY');
if (isNaN(today.getTime())) {
}
Note 2. Input as UTC
This function uses the local time zone offset value of the execution environment by default if the given string does not contain a time zone offset value. To make it use UTC instead, set the UTC option (the third argument) to true. If you want it to use any other time zone, you will need a plugin.
date.parse('11:14:05 PM', 'hh:mm:ss A');
date.parse('11:14:05 PM', 'hh:mm:ss A', true);
Note 3. Default Date Time
Default date is January 1, 1970
, time is 00:00:00.000
. Values not passed will be complemented with them:
date.parse('11:14:05 PM', 'hh:mm:ss A');
date.parse('Feb 2000', 'MMM YYYY');
Note 4. Max Date / Min Date
Parsable maximum date is December 31, 9999
, minimum date is January 1, 0001
.
date.parse('Dec 31 9999', 'MMM D YYYY');
date.parse('Dec 31 10000', 'MMM D YYYY');
date.parse('Jan 1 0001', 'MMM D YYYY');
date.parse('Jan 1 0000', 'MMM D YYYY');
Note 5. 12-hour notation and Meridiem
If use hh
or h
(12-hour) token, use together A
(meridiem) token to get the right value.
date.parse('11:14:05', 'hh:mm:ss');
date.parse('11:14:05 PM', 'hh:mm:ss A');
Note 6. Token invalidation
Any part of the given format string that you do not want to be recognized as a token should be enclosed in square brackets. They are considered comments and will not be parsed.
date.parse('12 hours 34 minutes', 'HH hours mm minutes');
date.parse('12 hours 34 minutes', 'HH [hours] mm [minutes]');
Note 7. Wildcard
Whitespace acts as a wildcard token. This token will not parse the corresponding parts of the date and time strings. This behavior is similar to enclosing part of a format string in square brackets (Token invalidation), but with the flexibility that the contents do not have to match, as long as the number of characters in the corresponding parts match.
date.parse('2015/01/02 11:14:05', 'YYYY/MM/DD');
date.parse('2015/01/02 11:14:05', 'YYYY/MM/DD ');
Note 8. Ellipsis
...
token ignores subsequent corresponding date and time strings. Use this token only at the end of a format string. The above example can be also written like this:
date.parse('2015/01/02 11:14:05', 'YYYY/MM/DD...');
compile(formatString)
- @param {string} formatString - A format string
- @returns {Array.<string>} A compiled object
If you are going to execute the format()
, the parse()
or the isValid()
so many times with one string format, recommended to precompile and reuse it for performance.
const pattern = date.compile('MMM D YYYY h:m:s A');
date.parse('Mar 22 2019 2:54:21 PM', pattern);
date.parse('Jul 27 2019 4:15:24 AM', pattern);
date.parse('Dec 25 2019 3:51:11 AM', pattern);
date.format(new Date(), pattern);
preparse(dateString, arg)
- @param {string} dateString - A date and time string
- @param {string|Array.<string>} arg - A format string or its compiled object
- @returns {Object} A pre-parsed result object
This function takes exactly the same parameters with the parse()
, but returns a date structure as follows unlike that:
date.preparse('Fri Jan 2015 02 23:14:05 GMT-0800', ' MMM YYYY DD HH:mm:ss [GMT]Z');
{
Y: 2015,
M: 1,
D: 2,
H: 23,
A: 0,
h: 0,
m: 14,
s: 5,
S: 0,
Z: 480,
_index: 33,
_length: 33,
_match: 7
}
This date structure provides a parsing result. You will be able to tell from it how the date string was parsed(, or why the parsing was failed).
isValid(arg1[, arg2])
- @param {Object|string} arg1 - A pre-parsed result object or a date and time string
- @param {string|Array.<string>} [arg2] - A format string or its compiled object
- @returns {boolean} Whether the date and time string is a valid date and time
This function takes either exactly the same parameters with the parse()
or a date structure which the preparse()
returns, evaluates the validity of them.
date.isValid('2015/01/02 23:14:05', 'YYYY/MM/DD HH:mm:ss');
date.isValid('29-02-2015', 'DD-MM-YYYY');
const result = date.preparse('2015/01/02 23:14:05', 'YYYY/MM/DD HH:mm:ss');
date.isValid(result);
transform(dateString, arg1, arg2[, utc])
- @param {string} dateString - A date and time string
- @param {string|Array.<string>} arg1 - A format string or its compiled object before transformation
- @param {string|Array.<string>} arg2 - A format string or its compiled object after transformation
- @param {boolean} [utc] - Output as UTC
- @returns {string} A formatted string
This function transforms the format of a date string. The 2nd parameter, arg1
, is the format string of it. Available token list is equal to the parse()
's. The 3rd parameter, arg2
, is the transformed format string. Available token list is equal to the format()
's.
date.transform('3/8/2020', 'D/M/YYYY', 'M/D/YYYY');
date.transform('13:05', 'HH:mm', 'hh:mm A');
addYears(dateObj, years[, utc])
- @param {Date} dateObj - A Date object
- @param {number} years - The number of years to add
- @param {boolean} [utc] - If true, calculates the date in UTC
Added in: v3.0.0
- @returns {Date} The Date object after adding the specified number of years
Adds years to a date object. Subtraction is also possible by specifying a negative value. If the third parameter is false or omitted, this function calculates based on the system's default time zone. If you need to obtain calculation results based on a specific time zone regardless of the execution system, consider using the addYearsTZ()
, which allows you to specify a time zone name as the third parameter. See PLUGINS.md for details.
const now = new Date();
const next_year = date.addYears(now, 1);
Exceptional behavior of the calculation for the last day of the month:
const now = new Date(Date.UTC(2020, 1, 29));
const next_year = date.addYears(now, 1, true);
const next_next_year = date.addYears(next_year, 1, true);
addMonths(dateObj, months[, utc])
- @param {Date} dateObj - A Date object
- @param {number} months - The number of months to add
- @param {boolean} [utc] - If true, calculates the date in UTC
Added in: v3.0.0
- @returns {Date} The Date object after adding the specified number of months
Adds months to a date object. Subtraction is also possible by specifying a negative value. If the third parameter is false or omitted, this function calculates based on the system's default time zone. If you need to obtain calculation results based on a specific time zone regardless of the execution system, consider using the addMonthsTZ()
, which allows you to specify a time zone name as the third parameter. See PLUGINS.md for details.
const now = new Date();
const next_month = date.addMonths(now, 1);
Exceptional behavior of the calculation for the last day of the month:
const now = new Date(Date.UTC(2023, 0, 31));
const next_month = date.addMonths(now, 1, true);
const next_next_month = date.addMonths(next_month, 1, true);
addDays(dateObj, days[, utc])
- @param {Date} dateObj - A Date object
- @param {number} days - The number of days to add
- @param {boolean} [utc] - If true, calculates the date in UTC
Added in: v3.0.0
- @returns {Date} The Date object after adding the specified number of days
Adds days to a date object. Subtraction is also possible by specifying a negative value. If the third parameter is false or omitted, this function calculates based on the system's default time zone. If you need to obtain calculation results based on a specific time zone regardless of the execution system, consider using the addDaysTZ()
, which allows you to specify a time zone name as the third parameter. See PLUGINS.md for details.
const now = new Date();
const yesterday = date.addDays(now, -1);
addHours(dateObj, hours)
- @param {Date} dateObj - A Date object
- @param {number} hours - The number of hours to add
@param {boolean} [utc] - If true, calculates the date in UTC Added in: v3.0.0
Removed in: v3.5.0
- @returns {Date} The Date object after adding the specified number of hours
Adds hours to a date object. Subtraction is also possible by specifying a negative value. The third parameter was deprecated in version 3.5.0. Regardless of what is specified for this parameter, the calculation results will not change.
const now = new Date();
const an_hour_ago = date.addHours(now, -1);
addMinutes(dateObj, minutes)
- @param {Date} dateObj - A Date object
- @param {number} minutes - The number of minutes to add
@param {boolean} [utc] - If true, calculates the date in UTC Added in: v3.0.0
Removed in: v3.5.0
- @returns {Date} The Date object after adding the specified number of minutes
Adds minutes to a date object. Subtraction is also possible by specifying a negative value. The third parameter was deprecated in version 3.5.0. Regardless of what is specified for this parameter, the calculation results will not change.
const now = new Date();
const two_minutes_later = date.addMinutes(now, 2);
addSeconds(dateObj, seconds)
- @param {Date} dateObj - A Date object
- @param {number} seconds - The number of seconds to add
@param {boolean} [utc] - If true, calculates the date in UTC Added in: v3.0.0
Removed in: v3.5.0
- @returns {Date} The Date object after adding the specified number of seconds
Adds seconds to a date object. Subtraction is also possible by specifying a negative value. The third parameter was deprecated in version 3.5.0. Regardless of what is specified for this parameter, the calculation results will not change.
const now = new Date();
const three_seconds_ago = date.addSeconds(now, -3);
addMilliseconds(dateObj, milliseconds)
- @param {Date} dateObj - A Date object
- @param {number} milliseconds - The number of milliseconds to add
@param {boolean} [utc] - If true, calculates the date in UTC Added in: v3.0.0
Removed in: v3.5.0
- @returns {Date} The Date object after adding the specified number of milliseconds
Adds milliseconds to a date object. Subtraction is also possible by specifying a negative value. The third parameter was deprecated in version 3.5.0. Regardless of what is specified for this parameter, the calculation results will not change.
const now = new Date();
const a_millisecond_later = date.addMilliseconds(now, 1);
subtract(date1, date2)
- @param {Date} date1 - A Date object
- @param {Date} date2 - A Date object
- @returns {Object} The result object of subtracting date2 from date1
const today = new Date(2015, 0, 2);
const yesterday = new Date(2015, 0, 1);
date.subtract(today, yesterday).toDays();
date.subtract(today, yesterday).toHours();
date.subtract(today, yesterday).toMinutes();
date.subtract(today, yesterday).toSeconds();
date.subtract(today, yesterday).toMilliseconds();
isLeapYear(y)
- @param {number} y - A year to check
- @returns {boolean} Whether the year is a leap year
date.isLeapYear(2015);
date.isLeapYear(2012);
isSameDay(date1, date2)
- @param {Date} date1 - A Date object
- @param {Date} date2 - A Date object
- @returns {boolean} Whether the two dates are the same day (time is ignored)
const date1 = new Date(2017, 0, 2, 0);
const date2 = new Date(2017, 0, 2, 23, 59);
const date3 = new Date(2017, 0, 1, 23, 59);
date.isSameDay(date1, date2);
date.isSameDay(date1, date3);
locale([locale])
- @param {Function|string} [locale] - A locale installer or language code
- @returns {string} The current language code
It returns the current language code if called without any parameters.
date.locale();
To switch to any other language, call it with a locale installer or a language code.
import es from 'date-and-time/locale/es';
date.locale(es);
See LOCALE.md for details.
extend(extension)
- @param {Object} extension - An extension object
- @returns {void}
It extends this library. See EXTEND.md for details.
plugin(plugin)
- @param {Function|string} plugin - A plugin installer or plugin name
- @returns {void}
Plugin is a named extension object. By installing predefined plugins, you can easily extend this library. See PLUGINS.md for details.
Browser Support
Chrome, Firefox, Safari, Edge, and Internet Explorer 6+.
License
MIT