0

I am trying to load date which is 270 prior from today. I tried the following code but looks like something is wrong.

var d = new Date();
alert(d.setDate(d.getDate() - 2).toString()); //2 is just that I tried some number

I want to display that in the following format too dd/mm/yyyy. Thanks

sahana
  • 601
  • 5
  • 12
  • 33
  • 1
    If you need to do a lot of date stuff, I recommend using [MomentJS](http://momentjs.com). It makes this sort of thing much easier (`moment().subtract(270, 'days').format('DD/MM/YYYY')` in your case). – GregL Jan 29 '16 at 04:24
  • Also answered here ... http://stackoverflow.com/questions/5495815/javascript-code-for-showing-yesterdays-date-and-todays-date/5495838 – LuvnJesus Jan 29 '16 at 04:27
  • Rayon's code is working really nice. But I would like to try MomentJs as well. I will try that out and let you know. Thanks @GregL – sahana Jan 29 '16 at 04:29
  • @GregL Thanks for letting me know the wonderful moment magic :-) It is really much easier as you said. – sahana Jan 29 '16 at 04:36
  • @GregL Can that be used even for date validations ? – sahana Jan 29 '16 at 04:37

1 Answers1

6

DATEOBJ.getDate will return you date

DATEOBJ.getMonth will return month(0-11)

DATEOBJ.getFullYear will return year(yyyy 4 digits)

function pad(n) {
  return (n < 10) ? ("0" + n) : n;
}
var d = new Date();
d.setDate(d.getDate() - 270);
alert(d);
alert(pad(d.getDate()) + '/' + pad(d.getMonth() + 1) + '/' + d.getFullYear());
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • 2
    This won't _quite_ satisfy the `dd/mm/yyyy` requirement, because the day and month won't have leading zeroes if < 10, which the `dd` and `mm` bit usually indicate. But that is pretty easily solved with a helper function. – GregL Jan 29 '16 at 04:30
  • 2
    @GregL, I just ignored that. Have updated my answer! – Rayon Jan 29 '16 at 04:35