How to generate array of string with the weekdays from the current weekday using moment - reactjs

Want to generate the dynamic array of string with the weekdays as a value inside the array for the list which I am using.
Required:=> If current weekday is Monday then array should be
['today','tomorrow','Wednesday','Thursday','Friday','Saturday','Sunday']
Array should be dynamic based on the current day.

To generate array with the weekday as a string here is the code.
const daysArray = () => {
const weekArray = [...Array(7 - moment().weekday())];
const today = new Date();
return weekArray.map((week, index) => {
const dayName = moment(today)
.add(index, "days")
.calendar()
.split(" at")[0];
const date = moment(today).add(index, "days").format(DATE_FORMAT);
return { value: dayName, name: dayName, date };
});
};
This will generate the array of object with dynamic weekdays inside it. If you will return only dayName then you'll get you're desired result.

Related

Why is date-fns isAfter and isBefore both false?

I have my current date as
const currentDate = format(new Date(2021, 4, 5), 'yyyy-MM-dd');
Which displays
Current Date is: 2021-05-05
Then I have "Manchester's game is ", formatDate('2021-05-04T14:00:00')
The formatDate function is
const formatDate = (date) => {
return format(new Date(date), 'yyyy-MM-dd');
};
Which displays Manchester's game is 2021-05-04
When I compare the two times using isAfter and isBefore, I get false for both.
I am expecting this
console.log(isAfter(currentDate, formatDate('2021-05-04T14:00:00')));
To log true, but it logs false!
Why is that?
The argument type of isAfter is Date | Number, but you put in string type (your formatDate function return string, and currentDate is also string), so it will not work.
const currentDate = new Date(format(new Date(2021, 4, 5), 'yyyy-MM-dd'));
const comparedDate = new Date(format(new Date('2021-05-04T14:00:00'), 'yyyy-MM-dd'));
console.log(currentDate); // Date type
console.log(comparedDate); // Date type
console.log(isAfter(currentDate, comparedDate)); // True

How to dynamically disable days in react datepicker

I am using React DatePicker .I want to disable days in date picker. I am able to doing so by passing day number like below so Monday Tuesday and Saturday get's disabled.But how do I achieve this dynamically? I am able to form array like this
var notAvailableDays=[1,2,6] // which should disable these days. How do I return this at once?
const isWeekday = (date) => {
const day = date.getDay(date);
return day !== 1 && day !== 2 && day !== 6;
}
;
You can do an array lookup like this
const notAvailableDays = [1,2,6];
const isDisabled = (date) => {
const day = date.getDay(date);
return notAvailableDays.includes(day);
}

ReactJs: Group data by today, current week, current year

I have data in the following format
[
0:{
address:n/a
booking_status:null
commission_total:"65000.00"
created_at;"Tue, Jun, 2020"
},
1:{
address:n/a
booking_status:null
commission_total:"68000.00"
created_at;"Thur, Jun, 2020"
}
]
I am looking to group the set of data as described the subject line in ReactJs. Will anyone assist please
The easiest way is to use some sort of library for handling dates, like date-fns which have some builtin functions like isSameWeek and isSameYear
https://date-fns.org/v2.0.0-alpha.2/docs/isSameYear
Then it will be easy as filtering the array and extracting the ones that match
const today = new Date();
const todayGroup = data.filter(item => isSameDay(new Date(item.created_at), today));
const weekGroup = data.filter(item => isSameWeek(new Date(item.created_at), today));
const yearGroup = data.filter(item => isSameYear(new Date(item.created_at), today));
You can use Moment
var REFERENCE = moment("2015-06-05"); // fixed just for testing, use moment();
var TODAY = REFERENCE.clone().startOf('day');
var YESTERDAY = REFERENCE.clone().subtract(1, 'days').startOf('day');
var A_WEEK_OLD = REFERENCE.clone().subtract(7, 'days').startOf('day');
function isToday(momentDate) {
return momentDate.isSame(TODAY, 'd');
}
function isYesterday(momentDate) {
return momentDate.isSame(YESTERDAY, 'd');
}
function isWithinAWeek(momentDate) {
return momentDate.isAfter(A_WEEK_OLD);
}
function isTwoWeeksOrMore(momentDate) {
return !isWithinAWeek(momentDate);
}
console.log("is it today? ..................Should be true: "+isToday(moment("2015-06-05")));
console.log("is it yesterday? ..............Should be true: "+isYesterday(moment("2015-06-04")));
console.log("is it within a week? ..........Should be true: "+isWithinAWeek(moment("2015-06-03")));
console.log("is it within a week? ..........Should be false: "+isWithinAWeek(moment("2015-05-29")));
console.log("is it two weeks older or more? Should be false: "+isTwoWeeksOrMore(moment("2015-05-30")));
console.log("is it two weeks older or more? Should be true: "+isTwoWeeksOrMore(moment("2015-05-29")));

Dynamic date selected and current month is not displayed

This is my problem link
I am passing dynamic date array and getting month based on the current date but it is not working.
This is reference link
You need to pass an array instead of function call in selectedDays and you are passing date parameter wrong in selectedDaysS function :
selectedDaysS = daysArr => {
let dataToSend = daysArr.map(a => {
let m = a.split('-');
return new Date(m[0], m[1], m[2]);
});
return dataToSend;
};
and inside render :
return (
<DayPicker
initialMonth={this.currentMonth()}
selectedDays={this.selectedDaysS(["2019-07-25"])}
/>
);
Here is live link : https://codesandbox.io/s/react-day-picker-examplesselected-nfbgz?fontsize=14

setState not working in React JS

I am trying to give few dates to state.periods array. But it is not working. My code is as follows.
class SmallTable extends Component {
constructor(props) {
super(props);
console.log(props.startDate)
this.state = {
turns: [],
periods: []
}
}
componentDidMount() {
//calculate years/ months and keep in one array
const today = new Date();
var periods1 = [];
if (this.props.period=="year") { //if year calculate from last year last date
const lastYearLastDate= new Date(new Date().getFullYear()-1, 11, 31)
periods1.push(lastYearLastDate.getFullYear()+"-"+(lastYearLastDate.getMonth()+1)+"-"+lastYearLastDate.getDate());
var lastYearFirstDate= new Date(lastYearLastDate.getFullYear()-1,0,1);
//for the remaining periods
for (var i=0;i<this.props.numberOfPeriods-1;i++) {
periods1.push(lastYearFirstDate.getFullYear()+"-"+(lastYearFirstDate.getMonth()+1)+"-"+lastYearFirstDate.getDate());
lastYearFirstDate = new Date(lastYearFirstDate.getFullYear()-1,0,1);
}
}
else if (this.props.period=="month") {//if month calculate from last month last date
var d=new Date(); // current date
d.setDate(1); // going to 1st of the month
d.setHours(-1); // going to last hour before this date even started.
var lastMonthLastDate = d;
periods1.push(lastMonthLastDate.getFullYear()+"-"+(lastMonthLastDate.getMonth()+1)+"-"+lastMonthLastDate.getDate());
//go to last month first date
var lastMonthFirstDate = new Date(lastMonthLastDate.getFullYear(), lastMonthLastDate.getMonth(),1);
//for the remaining periods
for (var i=0;i<this.props.numberOfPeriods-1;i++) {
periods1.push(lastMonthFirstDate.getFullYear()+"-"+(lastMonthFirstDate.getMonth()+1)+"-"+lastMonthFirstDate.getDate());
lastMonthFirstDate=new Date(lastMonthFirstDate.getFullYear(), lastMonthFirstDate.getMonth()-1,1);
}
}
console.log(periods1); -->prints ["2017-12-31", "2016-1-1", "2015-1-1", "2014-1-1"]
this.setState((prevState)=>{
return {
periods: prevState.periods.push(periods1)
}
});
console.log(this.state.periods) --> prints []
}
render() {
return ( <div></div>)
}
How to get values in periods1 to periods state. I am trying to insert periods1 array into state periods array. Those are strings. Pls suggest where the error might be.
You're setting this.state.periods to the result of a push operation. But push returns the new array length, not the array itself. Try this instead:
periods: [...prevState.periods, periods1]
push() doesn't return a value.
You should use:
this.setState((prevState)=>{
let old = prevState.periods.slice();
old.push(periods1);
return {
periods: old
}
});
You have a few issues.
For the code here:
return {
periods: prevState.periods.push(periods1)
}
You never want to mutate state. Instead, you should create a new array object and then add the data, like so:
return {
periods: prevState.periods.concat([periods1])
}
Secondly, your console.log is in the wrong place
console.log(this.state.periods) --> prints []
setState happens asynchronously and thus may not finish by the time your componentDidMount method returns. Instead, put that console.log inside your render function to see the new state.
If you expect this.state.periods to be an array of arrays ([["2017-12-31", "2016-1-1", "2015-1-1", "2014-1-1"]]) you can push your array following an immutable pattern using the spread operator :
this.setState((prevState) => ({
periods: [...prevState.periods, periods1]
}), () => { console.log(this.state.periods) } );
You can notice the function passed as second param of setState() is a callback to execute console.log() after the state update.
If you want to push periods1 values in this.state.periods you can do this :
this.setState((prevState) => ({
periods: [...prevState.periods, ...periods1]
}));
Try to make a copy of your original state, so that you can perform setState in an immutable fashion.
const periods = [...this.state.periods];
periods.push(periods1);
this.setState({periods: periods});

Resources