Javascript Date Utility Functions

With JavaScript programming, it is often useful to calculate the client’s local time, difference between dates, and format daes. Here are a few simple date utility functions.

Date Add function.

// see http://trentrichardson.com/2011/09/27/better-javascript-date-add-and-diff/
Date.prototype.add = function (part, amount) {
part = part.toLowerCase();
var map = {
years: 'FullYear', months: 'Month', weeks: 'Hours', days: 'Hours', hours: 'Hours',
minutes: 'Minutes', seconds: 'Seconds', milliseconds: 'Milliseconds',
utcyears: 'UTCFullYear', utcmonths: 'UTCMonth', weeks: 'UTCHours', utcdays: 'UTCHours',
utchours: 'UTCHours', utcminutes: 'UTCMinutes', utcseconds: 'UTCSeconds', utcmilliseconds: 'UTCMilliseconds'
}, mapPart = map[part];
if (part == 'weeks' || part == 'utcweeks') amount *= 168;
if (part == 'days' || part == 'utcdays') amount *= 24;
this['set' + mapPart](this['get' + mapPart]() + amount);
return this;
}

Date Difference function.


Date.prototype.diff = function (date2, parts) {
var d1 = new Date(this.getTime()),
d2 = new Date(date2.getTime()),
pm = d1 <= d2 ? 1 : -1,
result = {},
factors = { weeks: (1000 * 60 * 60 * 24 * 7), days: (1000 * 60 * 60 * 24),
hours: (1000 * 60 * 60), minutes: (1000 * 60), seconds: 1000, milliseconds: 1 };
if (parts === undefined)
parts = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'];
else if (typeof (parts) == "string")
parts = [parts];
for (var i = 0, l = parts.length; i < l; i++) {
var k = parts[i]; result[k] = 0;
if (factors[k] === undefined) {
inaWhile: while (true) {
d2.adjust(k, -1 * pm);
if ((pm === 1 && d1 > d2) || (pm === -1 && d1 < d2)) {
d2.adjust(k, 1 * pm);
break inaWhile;
}
result[k]++;
}
}
else {
var tmpDiff = Math.abs(d2.getTime() - d1.getTime());
result[k] = Math.floor(tmpDiff / factors[k]);
d2.adjust(k, result[k] * -1 * pm);
}
result[k] *= pm;
}
if (parts.length == 1)
return result[parts[0]];
return result;
}

Local Date function.


Date.prototype.localDateTime = function () {
return this.adjust('minutes', -(new Date().getTimezoneOffset()));
}

Date formating function.


// see http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript
var dateMarkers = {
d: ['getDate', function (v) { return ("0" + v).substr(-2, 2) }],
m: ['getMonth', function (v) { return ("0" + v).substr(-2, 2) }],
n: ['getMonth', function (v) {
var mthNames = ["Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return mthNames[v];
}],
w: ['getDay', function (v) {
var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
return dayNames[v];
}],
y: ['getFullYear'],
H: ['getHours', function (v) { return ("0" + v).substr(-2, 2) }],
M: ['getMinutes', function (v) { return ("0" + v).substr(-2, 2) }],
S: ['getSeconds', function (v) { return ("0" + v).substr(-2, 2) }],
i: ['toISOString', null]
};
Date.prototype.format = function (fmt) {
var date = this;
var dateTxt = fmt.replace(/%(.)/g, function (m, p) {
var rv = date[(dateMarkers[p])[0]]()
if (dateMarkers[p][1] != null) rv = dateMarkers[p][1](rv)
return rv
});
return dateTxt
}

Leave a comment

Who's the Coach?

Ben Ruiz Oatts is the insightful mastermind behind this coaching platform. Focused on personal and professional development, Ben offers fantastic coaching programs that bring experience and expertise to life.

Get weekly insights

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.