Skip to content

Instantly share code, notes, and snippets.

@ChillyBwoy
Created September 4, 2011 22:17
Show Gist options
  • Save ChillyBwoy/1193619 to your computer and use it in GitHub Desktop.
Save ChillyBwoy/1193619 to your computer and use it in GitHub Desktop.
JavaScript Date shift
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));
@gazon1
Copy link

gazon1 commented Aug 27, 2020

Great! Found your gist when completing js yandex course from coursera

@mick62
Copy link

mick62 commented May 17, 2021

// 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