Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
date-and-time
Advanced tools
The date-and-time npm package is a lightweight library for date and time manipulation in JavaScript. It provides a variety of functions for parsing, formatting, adding, subtracting, and comparing dates and times.
Formatting Dates
This feature allows you to format dates into various string representations. The format method takes a date object and a format string as arguments.
const date = new Date(2023, 9, 10);
const dateAndTime = require('date-and-time');
const formattedDate = dateAndTime.format(date, 'YYYY/MM/DD HH:mm:ss');
console.log(formattedDate); // Output: 2023/10/10 00:00:00
Parsing Dates
This feature allows you to parse date strings into JavaScript Date objects. The parse method takes a date string and a format string as arguments.
const dateAndTime = require('date-and-time');
const dateString = '2023/10/10 00:00:00';
const parsedDate = dateAndTime.parse(dateString, 'YYYY/MM/DD HH:mm:ss');
console.log(parsedDate); // Output: Tue Oct 10 2023 00:00:00 GMT+0000 (Coordinated Universal Time)
Adding and Subtracting Time
This feature allows you to add or subtract time units (days, months, years, etc.) from a date. The addDays and addMonths methods are used in this example.
const dateAndTime = require('date-and-time');
let date = new Date(2023, 9, 10);
date = dateAndTime.addDays(date, 5);
console.log(date); // Output: Sun Oct 15 2023 00:00:00 GMT+0000 (Coordinated Universal Time)
date = dateAndTime.addMonths(date, -1);
console.log(date); // Output: Fri Sep 15 2023 00:00:00 GMT+0000 (Coordinated Universal Time)
Comparing Dates
This feature allows you to compare dates. The isSameDay method checks if two dates fall on the same day.
const dateAndTime = require('date-and-time');
const date1 = new Date(2023, 9, 10);
const date2 = new Date(2023, 9, 15);
const isSameDay = dateAndTime.isSameDay(date1, date2);
console.log(isSameDay); // Output: false
Moment.js is a widely-used library for date and time manipulation. It offers extensive functionality for parsing, validating, manipulating, and formatting dates. Compared to date-and-time, Moment.js is more feature-rich but also larger in size.
date-fns is a modern JavaScript date utility library that provides a comprehensive set of functions for date manipulation. It is modular, allowing you to import only the functions you need, making it more lightweight compared to Moment.js. date-fns is similar to date-and-time in terms of functionality but offers a more functional programming approach.
Luxon is a modern library for working with dates and times in JavaScript. It is built by one of the Moment.js developers and offers a more modern API with better support for internationalization. Luxon is more feature-rich than date-and-time and is designed to be a more modern alternative to Moment.js.
This JS library is just a collection of functions for manipulating date and time. It's small, simple, and easy to learn.
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.
npm i date-and-time
3.6.0
parseTZ()
, enabled parsing of the missing hour during the transition from standard time to daylight saving time into a Date type.format()
with the z
token, fixed an issue where some short time zone names were incorrect.3.5.0
addYearsTZ()
, addMonthsTZ()
, and addDaysTZ()
to the timezone
plugin.addHours()
, addMinutes()
, addSeconds()
, and addMilliseconds()
.3.4.1
formatTZ()
would output 0:00 as 24:00 in 24-hour format in Node.js.import date from 'date-and-time';
const date = require('date-and-time');
<script type="module">
import date from '/path/to/date-and-time.es.min.js';
</script>
<script src="/path/to/date-and-time.min.js">
// You will be able to access the global variable `date`.
</script>
"type": "module"
in your package.json
or change your file extension from .js
to .mjs
.compilerOptions
of your tsconfig.json
are set to true
.{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
}
}
const now = new Date();
date.format(now, 'YYYY/MM/DD HH:mm:ss'); // => '2015/01/02 23:14:05'
date.format(now, 'ddd, MMM DD YYYY'); // => 'Fri, Jan 02 2015'
date.format(now, 'hh:mm A [GMT]Z'); // => '11:14 PM GMT-0800'
date.format(now, 'hh:mm A [GMT]Z', true); // => '07:14 AM GMT+0000'
const pattern = date.compile('ddd, MMM DD YYYY');
date.format(now, pattern); // => 'Fri, Jan 02 2015'
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'); // => '02-MM-2015'
date.format(new Date(), '[DD-[MM]-YYYY]'); // => 'DD-[MM]-YYYY'
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'); // => '11:14 PM GMT-0800'
date.format(new Date(), 'hh:mm A [GMT]Z', true); // => '07:14 AM GMT+0000'
You can also define your own tokens. See EXTEND.md for details.
date.parse('2015/01/02 23:14:05', 'YYYY/MM/DD HH:mm:ss'); // => Jan 2 2015 23:14:05 GMT-0800
date.parse('02-01-2015', 'DD-MM-YYYY'); // => Jan 2 2015 00:00:00 GMT-0800
date.parse('11:14:05 PM', 'hh:mm:ss A'); // => Jan 1 1970 23:14:05 GMT-0800
date.parse('11:14:05 PM', 'hh:mm:ss A', true); // => Jan 1 1970 23:14:05 GMT+0000 (Jan 1 1970 15:14:05 GMT-0800)
date.parse('23:14:05 GMT+0900', 'HH:mm:ss [GMT]Z'); // => Jan 1 1970 23:14:05 GMT+0900 (Jan 1 1970 06:14:05 GMT-0800)
date.parse('Jam 1 2017', 'MMM D YYYY'); // => Invalid Date
date.parse('Feb 29 2017', 'MMM D YYYY'); // => Invalid Date
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 |
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())) {
// Failure
}
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'); // => Jan 1 1970 23:14:05 GMT-0800
date.parse('11:14:05 PM', 'hh:mm:ss A', true); // => Jan 1 1970 23:14:05 GMT+0000 (Jan 1 1970 15:14:05 GMT-0800)
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'); // => Jan 1 1970 23:14:05 GMT-0800
date.parse('Feb 2000', 'MMM YYYY'); // => Feb 1 2000 00:00:00 GMT-0800
Parsable maximum date is December 31, 9999
, minimum date is January 1, 0001
.
date.parse('Dec 31 9999', 'MMM D YYYY'); // => Dec 31 9999 00:00:00 GMT-0800
date.parse('Dec 31 10000', 'MMM D YYYY'); // => Invalid Date
date.parse('Jan 1 0001', 'MMM D YYYY'); // => Jan 1 0001 00:00:00 GMT-0800
date.parse('Jan 1 0000', 'MMM D YYYY'); // => Invalid Date
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'); // => Jan 1 1970 11:14:05 GMT-0800
date.parse('11:14:05 PM', 'hh:mm:ss A'); // => Jan 1 1970 23:14:05 GMT-0800
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'); // => Invalid Date
date.parse('12 hours 34 minutes', 'HH [hours] mm [minutes]'); // => Jan 1 1970 12:34:00 GMT-0800
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.
// This will be an error.
date.parse('2015/01/02 11:14:05', 'YYYY/MM/DD'); // => Invalid Date
// Adjust the length of the format string by appending white spaces of the same length as a part to ignore to the end of it.
date.parse('2015/01/02 11:14:05', 'YYYY/MM/DD '); // => Jan 2 2015 00:00:00 GMT-0800
...
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...'); // => Jan 2 2015 00:00:00 GMT-0800
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); // => Mar 16 2020 6:24:56 PM
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, // Year
M: 1, // Month
D: 2, // Day
H: 23, // 24-hour
A: 0, // Meridiem
h: 0, // 12-hour
m: 14, // Minute
s: 5, // Second
S: 0, // Millisecond
Z: 480, // Timsezone offset
_index: 33, // Pointer offset
_length: 33, // Length of the date string
_match: 7 // Token matching count
}
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).
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'); // => true
date.isValid('29-02-2015', 'DD-MM-YYYY'); // => false
const result = date.preparse('2015/01/02 23:14:05', 'YYYY/MM/DD HH:mm:ss');
date.isValid(result); // => true
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.
// 3/8/2020 => 8/3/2020
date.transform('3/8/2020', 'D/M/YYYY', 'M/D/YYYY');
// 13:05 => 01:05 PM
date.transform('13:05', 'HH:mm', 'hh:mm A');
Added in: v3.0.0
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)); // => Feb 29 2020
const next_year = date.addYears(now, 1, true); // => Feb 28 2021
const next_next_year = date.addYears(next_year, 1, true); // => Feb 28 2022
Added in: v3.0.0
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)); // => Jan 31 2023
const next_month = date.addMonths(now, 1, true); // => Feb 28 2023
const next_next_month = date.addMonths(next_month, 1, true); // => Mar 28 2023
Added in: v3.0.0
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);
Added in: v3.0.0
Removed in: v3.5.0
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);
Added in: v3.0.0
Removed in: v3.5.0
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);
Added in: v3.0.0
Removed in: v3.5.0
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);
Added in: v3.0.0
Removed in: v3.5.0
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);
const today = new Date(2015, 0, 2);
const yesterday = new Date(2015, 0, 1);
date.subtract(today, yesterday).toDays(); // => 1 = today - yesterday
date.subtract(today, yesterday).toHours(); // => 24
date.subtract(today, yesterday).toMinutes(); // => 1440
date.subtract(today, yesterday).toSeconds(); // => 86400
date.subtract(today, yesterday).toMilliseconds(); // => 86400000
date.isLeapYear(2015); // => false
date.isLeapYear(2012); // => true
const date1 = new Date(2017, 0, 2, 0); // Jan 2 2017 00:00:00
const date2 = new Date(2017, 0, 2, 23, 59); // Jan 2 2017 23:59:00
const date3 = new Date(2017, 0, 1, 23, 59); // Jan 1 2017 23:59:00
date.isSameDay(date1, date2); // => true
date.isSameDay(date1, date3); // => false
It returns the current language code if called without any parameters.
date.locale(); // => "en"
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); // Switch to Spanish
See LOCALE.md for details.
It extends this library. See EXTEND.md for details.
Plugin is a named extension object. By installing predefined plugins, you can easily extend this library. See PLUGINS.md for details.
Chrome, Firefox, Safari, Edge, and Internet Explorer 6+.
MIT
FAQs
A Minimalist DateTime utility for Node.js and the browser
We found that date-and-time demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.