Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 15, 2012 16:41
Show Gist options
  • Save davybrion/3728759 to your computer and use it in GitHub Desktop.
Save davybrion/3728759 to your computer and use it in GitHub Desktop.
code snippet for "Who Needs Classes Anyway?" post
var MyNameSpace = MyNameSpace || {};
MyNameSpace.jsondateformatter = (function () {
var that = this;
var toDate = function (jsonDateString) {
var time = jsonDateString.replace(/\/Date\(([0-9]*)\)\//, '$1');
var date = new Date();
date.setTime(time);
return date;
};
var prefixWithZeroIfNecessary = function (number) {
return number < 10 ? '0' + number : number;
};
var dayAsDoubleDigitDayString = function (date) {
return prefixWithZeroIfNecessary(date.getDate());
};
var monthAsDoubleDigitMonthString = function (date) {
// for some reason, the result of getMonth is zero-based
return prefixWithZeroIfNecessary(date.getMonth() + 1);
};
var hourAsDoubleDigitHourString = function (date) {
return prefixWithZeroIfNecessary(date.getHours());
};
var minutesAsDoubleDigitMinuteString = function (date) {
return prefixWithZeroIfNecessary(date.getMinutes());
}
return {
toDate: function (jsonDateString) {
return that.toDate(jsonDateString);
},
toShortDateString: function (jsonDateString) {
var date = toDate(jsonDateString);
return dayAsDoubleDigitDayString(date) + '/' +
monthAsDoubleDigitMonthString(date) + '/' +
date.getFullYear();
},
toShortDateTimeString: function (jsonDateString) {
var date = toDate(jsonDateString);
return dayAsDoubleDigitDayString(date) + '/' +
monthAsDoubleDigitMonthString(date) + '/' +
date.getFullYear() + ' ' +
hourAsDoubleDigitHourString(date) + ':' +
minutesAsDoubleDigitMinuteString(date);
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment