Question

How can I subtract days from a date field?

Example:

Date Value is 03/10/2014 (mm/dd/yy),

I want to be able to subtract 6 weedays from it to get 03/03/2014

Can someone please help me get this.

Fiddle: to add 6 weekdays and disable all previous date values... From this fiddle whatever date is selected 6 weekdays must be subtracted from it.

i.e $("#txtFromDate").val() - 6 weekdays http://jsfiddle.net/7DHVr/8/

Thanks in advance

Was it helpful?

Solution

 var count = 10;
    //Add the 2 days of weekend in numer of days .
    var d = new Date();
    
    count = count + (parseInt(count/5))*2;
    d.setDate(d.getDate() -count);
    //suppose its ending on weekend day then increment them manually.
    if(d.getDay() == 6 ) d.setDate(d.getDate() -1); 
    if(d.getDay() == 0){ d.setDate(d.getDate() - 2);}; 
    alert(d);

it will substract all weekend day from whatever you want to substract day dynamically

OTHER TIPS

This can be done by subtracting from a Date type variable in javascript like so

var d = new Date("08/18/2009");
d.setDate(d.getDate()-5);

This will return a string of numbers representing that date then use

new Date(new Date().setDate(new Date().getDate()-5))

If you want to reformat it as a date the detailed answer is here Subtract days from a date in JavaScript

Just to add to the previous answer. You may want to use DateJs for easier use of date API.

So it would be like so:

 Date.today().addDays(-6)   

To delete 6 weekdays you just need to do

new Date().last().week()  - this will substruct 5 weekdays

and then if it is weekday then substruct 1 additional, if its Saturday then 2, if Sunday - 3

While you could accomplish this using the standard javascript Date object, I'd strongly recommend using a datetime library such as moment.js instead of trying to roll your own. Especially when you consider locale, timezones, leap years, months being different lengths, what day is start of week, etc.

Moment.js has weekday support and the documentation for it can be found here.

To subtract 6 weekdays from a date, you can do the following:

moment(date).weekday(-6);

Note that you can pass moment an existing javascript Date as well as a wide variety of ISO date formats or even just an array with [year, month, day, hour, minute, second] in it. If you provide no date, moment will default to the current date and time.

More about what can be parsed can be found here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top