Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix negative duration #1317

Merged
merged 6 commits into from
Jan 21, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions src/plugin/duration/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const wrapper = (input, instance, unit) =>
new Duration(input, unit, instance.$l) // eslint-disable-line no-use-before-define

const prettyUnit = unit => `${$u.p(unit)}s`
const roundNumber = number => number < 0 ? Math.ceil(number) : Math.floor(number)
Copy link

@johannpayer johannpayer Mar 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be replaced with Math.trunc(number), which is shorter.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems not supported in IE :-(


class Duration {
constructor(input, unit, locale) {
Expand Down Expand Up @@ -66,17 +67,17 @@ class Duration {

parseFromMilliseconds() {
let { $ms } = this
this.$d.years = Math.floor($ms / MILLISECONDS_A_YEAR)
this.$d.years = roundNumber($ms / MILLISECONDS_A_YEAR)
$ms %= MILLISECONDS_A_YEAR
this.$d.months = Math.floor($ms / MILLISECONDS_A_MONTH)
this.$d.months = roundNumber($ms / MILLISECONDS_A_MONTH)
$ms %= MILLISECONDS_A_MONTH
this.$d.days = Math.floor($ms / MILLISECONDS_A_DAY)
this.$d.days = roundNumber($ms / MILLISECONDS_A_DAY)
$ms %= MILLISECONDS_A_DAY
this.$d.hours = Math.floor($ms / MILLISECONDS_A_HOUR)
this.$d.hours = roundNumber($ms / MILLISECONDS_A_HOUR)
$ms %= MILLISECONDS_A_HOUR
this.$d.minutes = Math.floor($ms / MILLISECONDS_A_MINUTE)
this.$d.minutes = roundNumber($ms / MILLISECONDS_A_MINUTE)
$ms %= MILLISECONDS_A_MINUTE
this.$d.seconds = Math.floor($ms / MILLISECONDS_A_SECOND)
this.$d.seconds = roundNumber($ms / MILLISECONDS_A_SECOND)
$ms %= MILLISECONDS_A_SECOND
this.$d.milliseconds = $ms
}
Expand Down Expand Up @@ -136,7 +137,7 @@ class Duration {
if (pUnit === 'milliseconds') {
base %= 1000
} else if (pUnit === 'weeks') {
base = Math.floor(base / unitToMS[pUnit])
base = roundNumber(base / unitToMS[pUnit])
} else {
base = this.$d[pUnit]
}
Expand Down