date-template
- Easy function of 20 lines of code
- Date output in any format
- Change the date type
install
$ npm install -D date-template
template
~Y~
Year ****~M~
Month, from 01 to 12~D~
Day, from 01 to 31~Dw~
Day of the week 0-sunday, 6-saturday~h~
hourse~m~
minutes~s~
seconds~mm~
milliseconds
use
one parameter
var dateTemplate = require('date-template')
dateTemplate('~h~:~m~:~s~')
dateTemplate('~h~/~m~/~s~')
dateTemplate('hourse:~h~ minutes:~m~ seconds:~s~')
dateTemplate('~h~:WOW:~m~')
two parameters
var dateTemplate = require('date-template')
var oldDate = new Date()
oldDate.setHours(-3)
dateTemplate('~h~:~m~:~s~', oldDate)
var milliseconds = +new Date()
dateTemplate('~h~:~m~:~s~', milliseconds)
three parameters
var dateTemplate = require('date-template')
var middleware = (date) => {
var mounth = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
date['~M~'] = mounth[ date['~M~']-1 ]
return date
}
dateTemplate('Today is ~M~ ~D~, ~Y~', false, middleware)
source code
const dateTemplate = function( format, oldDate, middleware ){
let date = oldDate ? new Date(oldDate) : new Date();
let tmp = {
"~Y~": date.getFullYear(),
"~M~": date.getMonth() + 1,
"~D~": date.getDate(),
"~Dw~": date.getDay(),
"~h~": date.getHours(),
"~m~": date.getMinutes(),
"~s~": date.getSeconds(),
"~mm~": date.getMilliseconds
};
tmp = middleware ? middleware(tmp) : tmp
Object.keys(tmp).forEach( key => {
if( String(tmp[key]).length == 1 )
tmp[key] = 0 + String(tmp[key])
format = format.replace( key, tmp[key] )
})
return format
};