Created
December 6, 2016 10:45
-
-
Save romualdr/85001be7060578905b2246bd5618f08b to your computer and use it in GitHub Desktop.
Angular filter to transform a time unit to a date
This file contains 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
(function() { | |
'use strict'; | |
angular | |
.module('myApp') | |
.filter('DateFromTimeUnit', DateFromTimeUnit); | |
var DATE_METHODS = { | |
milliseconds: Date.prototype.setMilliseconds, | |
seconds: Date.prototype.setSeconds, | |
minutes: Date.prototype.setMinutes, | |
hours: Date.prototype.setHours, | |
days: Date.prototype.setDate, | |
years: Date.prototype.setFullYear | |
}; | |
/** | |
* Shorthands | |
**/ | |
DATE_METHODS.ms = DATE_METHODS.milliseconds; | |
DATE_METHODS.s = DATE_METHODS.seconds; | |
DATE_METHODS.m = DATE_METHODS.minutes; | |
DATE_METHODS.h = DATE_METHODS.hours; | |
DATE_METHODS.d = DATE_METHODS.days; | |
DATE_METHODS.y = DATE_METHODS.years; | |
function DateFromTimeUnit() { | |
return execute; | |
function execute (input, from) { | |
from = from || 'ms'; | |
if (isNaN(input) || !DATE_METHODS[from]) | |
return input; | |
var date = new Date(1970, 0, 1); | |
return DATE_METHODS[from].call(date, input) | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment