Reputation: 2266
I have a condition where i have to send start and end date to a child component from parent component.
In simple, i will send a start date and end date to the child component. The end date will be added to the start date (can be 3, 5, 7). i.e if start date is 2016-01-01 (and variable to add is 3) the end date is 2016-01-03.
However, i need to take in account another condition where i have to skip Sunday.
Lets say if 2016-01-02 is a sunday then the end date should be 2016-01-04.
The start date is initalized in getInitialState()
getInitialState(){
variable_to_add:5,
start_date: moment().format("YYYY-MM-DD"),
}
componentDidMount(){
this.setState({end_date:moment().add(Number(variable_to_add),'day').format("YYYY-MM-DD")
}
render(){
return <CallChild start_date={this.state.start_date} end_date={this.end_date}
},
Any suggesetions to accomplish or improve the code above will be highly appreciated.
Upvotes: 1
Views: 640
Reputation: 2266
I ended up using Pure Javascript with hints found in another page of Stack overflow Link.
formatDate:function(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
},
addWeekdays:function(date, days) {
var days = days-2;
date.setDate(date.getDate()+2);
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 ); // Add a day to get the date tomorrow
var check = date.getDay(); // turns the date into a number (0 to 6)
if (check == 0) {
// Do nothing it's the weekend (0=Sun & 6=Sat)
}
else{
counter++; // It's a weekday so increase the counter
}
}
}
return this.formatDate(date);
},
My getInitailState looks like this:
getInitialState: function() {
return {
date_from: moment().isoWeekday(1).format("YYYY-MM-DD"),
no_of_items : 7,
start_date: moment().add(2,'day').format("YYYY-MM-DD"),
value:0,
};
},
And my Render function looks like:
render(){
return <DayMenu weekday={(item.weekday).toString()} color={this.getRandomColor()} dataItem={dataItem} start_date={this.state.start_date} end_date={this.addWeekdays(new Date(this.state.start_date),this.state.no_of_items)}/>
Upvotes: 0
Reputation: 4600
You could create function like this for calculating needed date:
function addDaysWithoutSundays(date, daysToAdd) {
var tempEndDate = moment(date).add(daysToAdd, "day"),
countSundaysBetweenDates = function (startDate, endDate) {
var daysDiff = endDate.diff(startDate, 'days');
return Math.floor((startDate.day() + daysDiff)/ 7 );
},
countSundays = countSundaysBetweenDates(date, tempEndDate);
return moment(date).add(daysToAdd - countSundays, 'days');
}
You could try it here JsFiddle (You could find the result in console)
Upvotes: 2