sugar
Version:
A Javascript utility library for working with native objects.
44 lines (40 loc) • 1.18 kB
JavaScript
;
var LocaleHelpers = require('../var/LocaleHelpers'),
dateFormat = require('./dateFormat'),
classChecks = require('../../common/var/classChecks'),
assertDateIsValid = require('./assertDateIsValid'),
getAdjustedUnitForDate = require('./getAdjustedUnitForDate');
var isFunction = classChecks.isFunction,
localeManager = LocaleHelpers.localeManager;
function dateRelative(d, dRelative, arg1, arg2) {
var adu, format, type, localeCode, fn;
assertDateIsValid(d);
if (isFunction(arg1)) {
fn = arg1;
} else {
localeCode = arg1;
fn = arg2;
}
adu = getAdjustedUnitForDate(d, dRelative);
if (fn) {
format = fn.apply(d, adu.concat(localeManager.get(localeCode)));
if (format) {
return dateFormat(d, format, localeCode);
}
}
// Adjust up if time is in ms, as this doesn't
// look very good for a standard relative date.
if (adu[1] === 0) {
adu[1] = 1;
adu[0] = 1;
}
if (dRelative) {
type = 'duration';
} else if (adu[2] > 0) {
type = 'future';
} else {
type = 'past';
}
return localeManager.get(localeCode).getRelativeFormat(adu, type);
}
module.exports = dateRelative;