date-pattern
v1.0.3
Published
Format/parse dates using string patterns in nodejs/browser.
Downloads
2
Maintainers
Readme
date-pattern
Format/parse dates using string patterns in nodejs/browser. This module doesn't deal with any locale specific stuff.
Usage:
date.timezone //default timezone offset in minutes
date.baseyear //if 2 digit year is passed to date() then it is interpreted as a year near baseyear+/-50
date.format.pattern //default pattern for formatting: 'yyyy-MM-dd HH:mm:ss.SS ZZZ'
date.parse.pattern //default pattern for parsing: 'yyyy-MM-dd HH:mm:ss.SS ZZZ'
date([y, [M=1, [d=1, [H=0, [m=0, [s=0, [S=0, [timezone=date.timezone]]]]]]]])
date.format(t, [pattern=date.format.pattern], [timezone=date.timezone])
date.parse(str, [pattern=date.parse.pattern], [timezone=date.timezone])
date.parse.regex([pattern=date.parse.pattern], [timezone=date.timezone])
In pattern string:
- 'S': milliseconds;
- 's': seconds;
- 'm': minutes;
- 'H': hours;
- 'd': days;
- 'M': months;
- 'y': years;
- 'Z': timezone, use 'ZZZ' for now, I plan to change 'Z' and 'ZZ' functions;
- Two letters: two (three for 'SS') digits format (padded with zeros if needed);
- More letters: same as one letter, except 'yyyy';
- Any letter can be escaped with
\
(then it is interpreted as usual letter); - You can use the fact that in
parse
pattern string is converted to regex.
Examples
date(1970,1,1, 0,0,0,0, 0) //0
date() //same as +new Date()
date.timezone = -(3*60 + 15) //UTC-03:15 timezone offset
let t = date(2016,6,8, 9,4,2,12) //1465388342012
date.format(t, "yyyy-MM-dd HH:mm:ss.SS ZZZ") //"2016-06-08 09:04:02.012 UTC-03:15"
date.parse("2016-06-08 09:04:02.012 UTC-03:15", "yy-MM-dd HH:mm:ss.SS ZZZ") //1465388342012
See tests for more examples.
Installation
npm install date-pattern
Advanced installation
That's a browser script so you probably want just the main .js
file without node_modules
.
This command will produce just a single file in the current working directory:
Linux:
_npm_postinstall_args=justmain npm i date-pattern
Windows:
set _npm_postinstall_args=justmain & npm i date-pattern
- The error after installing this way is ok. It's a trick in
postinstall.js
to make npm safely remove the module fromnode_modules
(andnode_modules
itself if it is empty). - Initial underscore in
_npm_postinstall_args
denotes not standard npm environment variable that is used by postinstall script. - On Windows
_npm_postinstall_args
won't be reset after installation, so if you want to install the module normally after you should restart the shell or clear_npm_postinstall_args
manually (set _npm_postinstall_args=
).