Manuel Santi
Manuel Santi

Reputation: 1132

Current date minus n days formatted 'mm/dd/yyyy'

I am try to get in javascript the current date minus some delta days and format the result to mm/dd/yyyy. I write this piece of code:

  <script>
     function deltadata(d_delta) {
         var d = new Date();

         d.setDate(d.getDate() - d_delta);
         var dd = String(d).padStart(2, '0');
         var mm = String(d.getMonth +1).padStart(2, '0');
         var yyyy = d.getFullYear();

         today = mm + '/' + dd + '/' + yyyy;

         return today;
       }
  </script>

but the result is not what I expected

function getMonth() { [native code] }1/Wed Feb 19 2020 12:45:49 GMT+0100 (Central European Standard Time)/2020

someone can help me, please?

so many thanks in advance

Upvotes: 0

Views: 173

Answers (1)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

You may employ Date.prototype.toLocaleDateString() for that purpose, specifying format options accordingly:

const deltaDate = n => {
  const today = new Date()
  today.setDate(today.getDate() - n)
  return today
    .toLocaleDateString('en-US', {month:'2-digit',day:'2-digit',year:'numeric'})
}

console.log(deltaDate(3))

Upvotes: 3

Related Questions