bubble.js (1774B)
1import absFloor from '../utils/abs-floor'; 2import absCeil from '../utils/abs-ceil'; 3 4export function bubble() { 5 var milliseconds = this._milliseconds, 6 days = this._days, 7 months = this._months, 8 data = this._data, 9 seconds, 10 minutes, 11 hours, 12 years, 13 monthsFromDays; 14 15 // if we have a mix of positive and negative values, bubble down first 16 // check: https://github.com/moment/moment/issues/2166 17 if ( 18 !( 19 (milliseconds >= 0 && days >= 0 && months >= 0) || 20 (milliseconds <= 0 && days <= 0 && months <= 0) 21 ) 22 ) { 23 milliseconds += absCeil(monthsToDays(months) + days) * 864e5; 24 days = 0; 25 months = 0; 26 } 27 28 // The following code bubbles up values, see the tests for 29 // examples of what that means. 30 data.milliseconds = milliseconds % 1000; 31 32 seconds = absFloor(milliseconds / 1000); 33 data.seconds = seconds % 60; 34 35 minutes = absFloor(seconds / 60); 36 data.minutes = minutes % 60; 37 38 hours = absFloor(minutes / 60); 39 data.hours = hours % 24; 40 41 days += absFloor(hours / 24); 42 43 // convert days to months 44 monthsFromDays = absFloor(daysToMonths(days)); 45 months += monthsFromDays; 46 days -= absCeil(monthsToDays(monthsFromDays)); 47 48 // 12 months -> 1 year 49 years = absFloor(months / 12); 50 months %= 12; 51 52 data.days = days; 53 data.months = months; 54 data.years = years; 55 56 return this; 57} 58 59export function daysToMonths(days) { 60 // 400 years have 146097 days (taking into account leap year rules) 61 // 400 years have 12 months === 4800 62 return (days * 4800) / 146097; 63} 64 65export function monthsToDays(months) { 66 // the reverse of daysToMonths 67 return (months * 146097) / 4800; 68}