0

I am trying to set start and end date in date picker where start date is week before current date and end date is week after start date. In certain condition it gives me 0 for start date. Can anyone look into code below and help me to get proper date range when current date is first day of the month or last date of the month. Thanks for your help.

 var date = new Date();

//When current date was less then 7 in some situation it giving me error. So, I am checking current date and randomly subtract 3. //if current date is less then 7 then get the last day of the previous month if (date.getDate() <= 7) {

    day = new Date(date.getFullYear(), date.getMonth(), 0);        
    startdate = day.getDate() - 3;
    month = day.getMonth() + 1;
    year = day.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = day;
    console.log("App Config: lasy day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}

else {

    startdate = date.getDate() - 7;
    month = date.getMonth() + 1;
    year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = day;

    console.log("App Config: day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}

return month + "/" + startdate + "/" + year;
2
  • Which datepicker you using? Commented Feb 20, 2015 at 14:45
  • 1
    You don't need to deal with wrapping the month yourself. If you use date.setDate(date.getDate() - 7) it will figure it out automatically. Commented Feb 20, 2015 at 14:46

2 Answers 2

1

Have you tried this:

var dt = new Date();
var weekBefore = dt.setDate(dt.getDate() - 7);
var weekAfter = dt.setDate(dt.getDate() + 7);

JavaScript will figure it out automatically the date 7 days before and after!

Sign up to request clarification or add additional context in comments.

1 Comment

Above code will still work if current date is less then 7. For example, if current date is 02/05/2015 then according to your code will it give 01/28/2015.
0

If you are ok with plugins I would suggest Moment.js which is great for date handling. Adding a week would be as easy as

var inOneWeek = moment().add(1, 'weeks');//.format('DD/MM/YYYY'); if u want it in DD/MM/YYYY format
var oneWeekAgo = moment().add(-1, 'weeks');//.format('DD/MM/YYYY');

otherwise @sabotero's answer would do as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.