Avatar

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.

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 !

403e57e2be130d2218f992b86dfa8260

Gary Haran

October 1, 2007, October 01, 2007 10:41, permalink

2 ratings. Login to rate!

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())
A969cbe277419ae0af0acee58f4cfa15

Dan Simard

October 1, 2007, October 01, 2007 11:28, permalink

1 rating. Login to rate!

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())
403e57e2be130d2218f992b86dfa8260

Gary Haran

October 1, 2007, October 01, 2007 11:47, permalink

2 ratings. Login to rate!

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())
918aabb05e77cfa8e40d2a76a5168326

travis

October 1, 2007, October 01, 2007 11:55, permalink

2 ratings. Login to rate!

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())
B9c4fc6020513ae8896e075f54616af2

Sean Catchpole

October 1, 2007, October 01, 2007 21:41, permalink

1 rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel