Skip to content

Instantly share code, notes, and snippets.

@markbates
Created May 11, 2011 19:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save markbates/967085 to your computer and use it in GitHub Desktop.
Save markbates/967085 to your computer and use it in GitHub Desktop.
Example: Rails-style date/time helpers in CoffeeScript
Number::seconds = ->
@ * 1000
Number::minutes = ->
@seconds() * 60
Number::minute = Number::minutes
Number::hours = ->
@minutes() * 60
Number::hour = Number::hours
Number::ago = ->
new Date(new Date().valueOf() - @)
Number::from_now = ->
new Date(new Date().valueOf() + @)
console.log 2.seconds()
console.log new Date()
console.log 2.seconds().ago()
console.log 10.seconds().from_now()
console.log 1.minutes().from_now()
console.log 1.hours().from_now()
console.log 1.hour().from_now()
console.log 1.hour().ago()
Number.prototype.seconds = function() {
return this * 1000;
};
Number.prototype.minutes = function() {
return this.seconds() * 60;
};
Number.prototype.minute = Number.prototype.minutes;
Number.prototype.hours = function() {
return this.minutes() * 60;
};
Number.prototype.hour = Number.prototype.hours;
Number.prototype.ago = function() {
return new Date(new Date().valueOf() - this);
};
Number.prototype.from_now = function() {
return new Date(new Date().valueOf() + this);
};
console.log((2).seconds());
console.log(new Date());
console.log((2).seconds().ago());
console.log((10).seconds().from_now());
console.log((1).minutes().from_now());
console.log((1).hours().from_now());
console.log((1).hour().from_now());
console.log((1).hour().ago());
@jashkenas
Copy link

Looks nice, but you don't have to put () in front of a function that expects no arguments. Just -> will do nicely.

@markbates
Copy link
Author

Good tip. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment