简体   繁体   中英

Any built-in method to get boundary dates for a date in day, week and month view in a calendar?

I need to send boundary dates of a selected date(from a date picker) to the server based on present view is Day or Week or Month. Example as shown given below

Ex: If the day is 25-01-2016 and

1. In "Day" View I need to send :
fromDate: "25012016", 
toDate:"25012016"

2. "Week" view(consider Monday as first day of the week as the calendar view in my screen showing the same) :
fromDate: "25012016", 
toDate:"31012016"

3."Month" view:
fromDate: "01012016", 
toDate:"31012016"

Not aware of any built in function but you can easily get

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

Week

//var currentDate = new Date();
var currentDate = new Date(2016,0,19);
var dayOfWeek = currentDate.getDay();
console.log( dayOfWeek );
dayOfWeek = (dayOfWeek + 6 )%7; //calibrate it for Monday to Sunday
currentDate.setDate( currentDate.getDate() + (-dayOfWeek ) );  //first day of week accomodating +1 for making Monday as first day
document.body.innerHTML += "<br>" + currentDate.toString();
currentDate.setDate( currentDate.getDate() + 7 ); //last day of week 
document.body.innerHTML += "<br>" + currentDate.toString();

Month

currentDate = new Date();
currentDate.setDate( 1 ); //first day of current month
document.body.innerHTML += "<br>" + currentDate.toString();
currentDate.setMonth( currentDate.getMonth() + 1 ); //first day of next month
currentDate.setDate( currentDate.getDate() + (-1) ); //last day of current month 
document.body.innerHTML += "<br>" + currentDate.toString();

Thanks all for the help!

With Momentjs, I did my job.

// type can be "Day" or "Week" or "Month"
var getBoundaryDates = function(selecteddate, type){            
        var fromd = moment(selecteddate).startOf(type).format('YYYY-MM-DD');
        var tod = moment(selectddate).endOf(type).format('YYYY-MM-DD');
        if(type == 'Week') {
            var dayToSubtract = selecteddate.getDay() == 0 ? 7 : selecteddate.getDay();
            fromd = moment(new Date(selecteddate).setDate((selecteddate.getDate() - dayToSubtract) +1)).format('YYYY-MM-DD');
            tod = moment(new Date(selecteddate).setDate((selecteddate.getDate() - dayToSubtract) +7)).format('YYYY-MM-DD');
        }
        return {
            fromd : fromd,
            tod : tod
        }
    }

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