Created
September 4, 2011 22:17
-
-
Save ChillyBwoy/1193619 to your computer and use it in GitHub Desktop.
JavaScript Date shift
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
var shiftDate = function(date, what, count) { | |
var proc1 = 'get' + what, | |
proc2 = 'set' + what; | |
var value = Date.prototype[proc1].call(date); | |
Date.prototype[proc2].call(date, value + count); | |
return date; | |
} | |
console.log(shiftDate(new Date, 'Date', -21)); | |
console.log(shiftDate(new Date, 'Date', 42)); | |
console.log(shiftDate(new Date, 'Month', -4)); | |
console.log(shiftDate(new Date, 'FullYear', 10)); |
// The typescript version
type DateScaleLevel = 'FullYear' | 'Month' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds';
export const shiftDate = (level: DateScaleLevel) => {
const getter = Date.prototype[('get' + level) as keyof Date] as () => number;
const setter = Date.prototype[('set' + level) as keyof Date] as (value: number) => number;
return (date: Date, diff: number): number => {
const currentValue = getter.call(date);
return setter.call(date, currentValue + diff);
};
};
console.log(shiftDate('Date')(new Date, , -21));
console.log(shiftDate('Date')(new Date, , 42));
console.log(shiftDate('Month')(new Date, -4));
console.log(shiftDate('FullYear')(new Date, 10));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great! Found your gist when completing js yandex course from coursera