Len
Len

Reputation: 554

How to substract 1 month from selected date with the right format

I want to substract 1 month from the selected date and get it in this format mm/dd/yyyy

self.SelectedDate = "02/22/2018";
var temp = new Date(self.SelectedDate);
    temp.setDate(temp.getDate() - 30);

but the result I get is Mon Jan 08 2018 00:00:00 GMT+0800 (Malay Peninsula Standard Time)

This is just a very small part in my program so I don't want to download a library just for this. I am using AngularJS, is there a way to get what I want without downloading or adding angular filters?

Upvotes: 3

Views: 187

Answers (4)

Romildo da Silva
Romildo da Silva

Reputation: 291

The constructor of date accept:

new Date(year, month [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

on your case:

new Date( year, month, day )

Below functions solves your problem:

function formatDate(date) {
    let parts = date.split('/');
    date = new Date( parts[2], parts[0]-2, parts[1] )
    return addZero( date.getMonth() + 1) +
        addZero( date.getDate()) + date.getFullYear();
}

function addZero(number) {
    return ('0' + number).slice(-2) + '/' ;
}

// test
var dateN = '01/31/2018'
console.log( formatDate(dateN) );

Upvotes: 0

Afzal
Afzal

Reputation: 71

In line with some of the comments and answers. I wrote a function that you can call which will format the date as you want it.

It accepts a JS Date as the only argument

var formatDate = (date) => {
   var month = date.getMonth() + 1
   var day = date.getDate()
   var year = date.getFullYear()

   //Pad the month and/or day with "0" if its not two digits
   if(month < 10) month = `0${month}`
   if(day < 10) day = `0${day}`

   return `${month}/${day}/${year}`
}

JS Bin example

Upvotes: 2

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23399

The Date constructor does not accept a string in this format.

self.SelectedDate = "02/22/2018";
var p = self.SelectedDate.split("/");
var temp = new Date(p[2],p[0]-1,p[1]);
    temp.setDate(temp.getDate() - 30);
const pad = n=>("0"+n).slice(-2);
var f = [pad(temp.getMonth()+1),pad(temp.getDate()),temp.getFullYear()].join("/");
console.log(f);

Upvotes: 3

Bibek Shah
Bibek Shah

Reputation: 429

You have the time stored in the temp variable. So, you can do something like this to get it in your format.

formattedDate = ("0" + (temp.getMonth() + 1)).slice(-2) + "/" + temp.getDate() + "/" + temp.getFullYear();

Upvotes: 1

Related Questions