-6

I have this Javascript function that takes X number of days and returns a date in the past

 var GetDateInThePastFromDays = function (days) {

        var today = new Date();
        _date = new Date(today.getFullYear(), today.getMonth(), today.getDate() - days);

        return _date.toLocaleDateString();
    }

That works absolutely fine, but it returns the date as 06/01/2016 but I want it returned as 06-01-2016 but I can't seem to find out how to do it correctly.

Morten Hagh
  • 2,055
  • 8
  • 34
  • 66
  • 5
    http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript – Teemu Jan 06 '16 at 08:55
  • 6
    you got 660 rep points but didn't think to google "format javascript date" ?????? – Scott Selby Jan 06 '16 at 08:57
  • use like this, var today = new Date(); alert((today.getMonth() + 1) + '-' + today.getDate() + '-' + today.getFullYear()); Cheers! – Mysterion Jan 06 '16 at 09:01

1 Answers1

1

.toLocaleDateString() returns a string formatted according to the user's locale, meaning the format will match whatever is set on the user's machine. For me, that's 06/01/2016 but for an American it might be 01/06/2016 (because they're weird like that).

You should define your own format if you want a fixed one:

function pad(n) {return (n<10 ? "0" : "")+n;}
return pad(_date.getDate()) + "-" + pad(_date.getMonth()+1) + "-" + _date.getFullYear();
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592