Created
September 15, 2012 16:41
-
-
Save davybrion/3728759 to your computer and use it in GitHub Desktop.
code snippet for "Who Needs Classes Anyway?" post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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