hourjs
Sometimes we deal with TIME ONLY strings like '10:01' or '10:01:02' which are considered wrong formats by dayjs or momentjs.
Features
- Parse, validate, manipulate, and display times in JavaScript
- Same modern API with dayjs and momentjs
- Written with TypeScript, 100% unit test coverage
- Support mini-program
- 0 dependency
Quick Start
$ yarn add hourjs
import hourjs from 'hourjs'
// Avaliable API for now
hourjs().isSame()
hourjs('18:44').isBetween('18:01', '18:03', 'hour', '[]')
hourjs('18:44').isBefore('18:44')
hourjs('18:44:01').isSameOrBefore('18:44:01')
hourjs('18:44:01').isAfter('18:44')
hourjs('18:44').isSameOrAfter('18:44:01')
hourjs().add(2, 'hour')
hourjs().subtract(3, 'minute')
hourjs().preciseDiff()
arguments format (for all API)
- Empty
hourjs()
means now - HH:mm
hourjs('01:02')
- HH:mm:ss
hourjs('23:59:59')
- Instance of hourjs
hourjs(hourjs('01:02'))
isBetween
- The first argument and the second argument can be different in format
isBetween('01:02', '23:59:59')
-
There's a third argument that controls inclusion relation, '[' indicates inclusion, '(' indicates exclusion
hourjs('01:02').isBetween('01:02', '23:59:59', '(]')
// will return falsepossible options:
- [] (default)
- ()
- (]
- [)
preciseDiff
can be used to calculate a count down
hourjs('01:02:03').preciseDiff('02:03:04')
will return:
{
hours: 1,
minutes: 1,
seconds: 1,
isSame: false,
isAfter: false,
isBefore: true,
isSameOrAfter: false,
isSameOrBefore: true
}
What's different comparing to use dayjs for same purpose
-
hourjs is more concise
-
dayjs do not unify the usage between ordinary date strings and none-date strings
-
dayjs will return false when you pass the wrong arguments instead of throwing an error
-
dayjs didn't take in the preciseDiff PR, the plugin author publish dayjs-precise-range under ISC licence
duration plugin of dayjs can be used for diff calculation, but it's indirect to indicate sequence of time
import dayjs from 'dayjs'
[
'isBetween',
'isSameOrAfter',
'isSameOrBefore',
'customParseFormat',
'duration',
].map(v => {
dayjs.extend(require(`dayjs/plugin/${v}.js`))
})
// isBefore
dayjs('10:13', 'HH:mm').isBefore(dayjs('10:13:59', 'HH:mm:ss'))
// isAfter
dayjs('10:13', 'HH:mm').isAfter(dayjs('10:13:59', 'HH:mm:ss'))
// isSame
dayjs('10:13', 'HH:mm').isSame(dayjs('10:13:59', 'HH:mm:ss'))
// isSameOrAfter
dayjs('01:02', 'HH:mm').isSameOrAfter(dayjs('01:02', 'HH:mm'))
// isSameOrBefore
dayjs('01:02', 'HH:mm').isSameOrBefore(dayjs('01:02', 'HH:mm'))
// isBetween
dayjs('01:02', 'HH:mm').isBetween(dayjs('01:02', 'HH:mm'), dayjs('23:59:59', 'HH:mm'), null, '(]')
// add
dayjs('01:02', 'HH:mm').add(1, 'hour').format('HH:mm')
// subtract
dayjs('01:02', 'HH:mm').subtract(1, 'hour').format('HH:mm')
// duration
// diff的调用者晚于参数时 结果为正数
dayjs.duration(dayjs('2020-01-01 01:01:01').diff()).$d