I am trying to get specific date in java script.
What I am trying to do is.
I have variable called frequency
Which can be Daily
, Weekly
and Monthly
if(frequency=="daily")
{
date='current_date -2 days';
}
else if ( frequency== 'weekly')
{
date='current_date -8 days';
}
else if ( frequency == 'monthly')
{
date='current_date -32 days';
}
This is the way I get current date with required format.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hh = today.getHours();
var min = today.getMinutes();
var ss = today.getSeconds();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
// today = mm+'/'+dd+'/'+yyyy;
today = yyyy + "-" + mm + "-" + dd + " " + hh + ":" + mm + ":" + ss ;
alert("Today's date :"+today);
But, I am facing problem in subtracting the days
can anyone give an idea how can I achieve this.
You can simply do this:
function setDate(frequency) {
var today = new Date(),
date;
if (frequency == "daily") {
date = today.getTime() - (2*24*60*60*1000); // 2 days 24 hrs 60 mins 60 secs 1000 ms
} else if (frequency == 'weekly') {
date = today.getTime() - (8*24*60*60*1000);
} else if (frequency == 'monthly') {
date = today.getTime() - (32*24*60*60*1000);
}
return new Date(date);
}
document.querySelector('pre').innerHTML = setDate('monthly');
<pre></pre>
You need to convert days into time in ms
miliseconds to convert it in time then you can subtract it from current time in ms
after it you can return it as a new Date(date);
.