简体   繁体   中英

Javascript/Ajax How to find date before number of weeks entered by user

i am fetching one date "Due date " from system for certain application I have one requirement like user will enter number of weeks dynamically and from those number of weeks I have to find the date using following formula :-

Due Deadline = Due date-weeks

please help if you have any soln!!! --Snehal

There is a Date object built into JS. Also, most JS libraries have Date objects with even more functionality.

Using the date object, you can convert it to a timestamp and subtract the number of seconds in a week multiplied by the number of weeks the user entered, rounding down or up depending on your needs.

Read more about the JS Date object at: http://www.w3schools.com/jsref/jsref_obj_date.asp

try this:

var  time = new Date().getTime();
var week =604800000;// 7*24*3600*1000;
var threeWeeksBefore = new Date(time - 3 * week);
var sixWeeksFromNow  = new Date(time + 6 * week);

http://jsfiddle.net/aqwEv/

You can avoid daylight savings oddities by adding days instead of seconds

Date.prototype.addWeeks= function(n, hours, mins){
    var due= new Date(this);
    if(typeof hours== 'number'){
        if(typeof mins!== 'number') mins= 0;
        due.setHours(hours, mins, 0, 0);
    }
    due.setDate(due.getDate()+(n*7));
    return due;
}

new Date().addWeeks(2) // same time as Date Tue Sep 20 2011 09:53:56

new Date().addWeeks(2, 0) // midnight Tue Sep 20 2011 00:00:00

new Date().addWeeks(2, 7,30) //set hours && minutes Tue Sep 20 2011 07:30:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM