1 2 3 4
var d = new Date() d.setDate(d.getDate()-1) var yesterday = (d.getMonth()+1+"/"+d.getDate()+"/"+d.getFullYear()) document.write(yesterday)
Refactorings
No refactoring yet !
Gary Haran
October 1, 2007, October 01, 2007 10:41, permalink
You should consider extending prototype rather than doing this procedurally.
1 2 3 4 5
Date.prototype.getYesterday = function(){ return new Date(this.getTime() - (24 * 60 * 60 * 1000)); } var d = new Date(); document.write(d.getYesterday())
Dan Simard
October 1, 2007, October 01, 2007 11:28, permalink
I simplified things a little bit. I also made the "yesterday" relative to the date object. That way, you can have the "yesterday" of any date and not just the yesterday of today.
1 2 3 4 5
Date.prototype.getYesterday = function(){ return d.setDate(d.getDate()-1); } var d = new Date(); document.write(d.getYesterday())
Gary Haran
October 1, 2007, October 01, 2007 11:47, permalink
Hey Dan, glad you picked up the getDate trick... but it seems like you meant "this" rather than "d".
1 2 3 4 5
Date.prototype.getYesterday = function(){ return this.setDate(this.getDate()-1); } var d = new Date(); document.write(d.getYesterday())
travis
October 1, 2007, October 01, 2007 11:55, permalink
I would even extend it a bit further, although it may be overkill for your application.
1 2 3 4 5 6 7 8
Date.prototype.addDays = function(daysToAdd){ return this.setDate(this.getDate() + daysToAdd); } Date.prototype.getYesterday = function(){ return this.addDays(-1); } var d = new Date(); document.write(d.getYesterday())
Sean Catchpole
October 1, 2007, October 01, 2007 21:41, permalink
Those are great solutions that allow for re-use. Often in javascript a simple one-line throwaway is sufficient.
1
document.write( (new Date()).getDate()-1 ); //Yesterday
Display yesterday's date. Initially, what would happen on the first of every month, the day was displayed as "0" which was not acceptable. This is what I came up with, but I'm not sure if there is a better way to do this in JavaScript.