I am facing an issue in javascript dates, i want to match slot dates comparing start_date or end_date.
my component
{this.state.data && this.state.data.length
? this.state.data
.filter(data => {
const date = new Date(data.start_date);
const enddate = new Date(data.end_date);
console.log(date); //start
console.log(enddate); //end
return date > prevDate && date < nextDate;
})
.map(({ cust_full_name, start_date }, index) => (
<div class="row" key={index}>
slot: {index + 1}
<p>{start_date}</p>
<p>{cust_full_name}</p>
</div>
))
: null}
working demo:
https://codesandbox.io/s/lucid-dream-gl3l7?file=/src/App.js
what should i do? can anyone help me?
Edit: Your slot values in your state are in arrays but when you pass them to date you aren't accessing the string value.
slot1 : ["date"]
Incorrect: new Date[slot1]
Correct: new Date[slot[0]]
In your sandbox it seems you never populated newprevious and newseconddate here:
const prevDate = new Date(this.state.newprevious);
const nextDate = new Date(this.state.newseconddate);
Once i populated those in the above state section, it seems to work. I do also suggest maybe turning Date into something like epoch; so the numbers are easier to work with (Get epoch for a specific date using Javascript)
Related
I created a calendar using React and date-fns, following this tutorial - https://medium.com/#w.difulvio523/create-a-custom-hooks-calendar-in-react-e50bbba456e1
Then I added a functionality in cell function, where it creates and mapped the days in month,
to fetch the schedule from the mongoDB.
But the schedule renders on its actual day + 1, t.ex if the schedule is today, it will render on date tomorrow, in Europe/Berlin time zone.
But it will render correctly in Brazil time zone.
You can check it here in this codepen - https://codepen.io/luispaulopinto/pen/abNNmZa
this is how that cell function looks like
const cells = () => {
const monthStart = startOfMonth(currentDate)
const monthEnd = endOfMonth(monthStart)
const startDate = startOfWeek(monthStart, {weekStartsOn: 1})
const endDate = endOfWeek(monthEnd)
const dateFormat = "d"
const rows = []
let days = []
let day = startDate
let formattedDate = ""
while (day < endDate) {
for (let i = 0; i < 7; i++) {
formattedDate = format(day, dateFormat)
const cloneDay = day
//here get the schdules
//and render in cells.
//if the schduels.date is same as 'day' or 'clone day',
//render <Link/> to Exercise element with corresponding ID
// //split and reforamt the cloneDay to compare with schedule object's date
const formatCloneDay = day.toISOString().split('T')[0]
// console.timeLog(formatCloneDay)
const scheduleElements = exerciseScheduleArray.map(schedule => {
//reformat for the compare with formatCloneday
const formatScheduleDate = schedule.date.split('T')[0]
const hasMatchingDays = formatScheduleDate.toString() === formatCloneDay.toString()
if(hasMatchingDays) {
return (
<Link className="schedule-link" to={`/exercise/${schedule.exercise}`} key={schedule._id}>
<span>{schedule.bodySection} {schedule.duration}</span>
</Link>
)
}
})
days.push(
<div
className={`column cell ${
!isSameMonth(day, monthStart) ? "disabled" :
isSameDay(day, selectedDate) ? "selected" : "" }`}
key={day}
onClick={() => onClickDate(cloneDay)}
>
<span className="number">{formattedDate}</span>
<span className="bg">{formattedDate}</span>
{scheduleElements}
</div>
)
//this will increase the day value by 1 each time it iterates
day = addDays(day, 1)
}
rows.push(
<div className="row" key={day}> {days} </div>
)
//if 7 days has been pushed to the rows, delete the days
//so it could start a new row with new days
days = []
}
return <div className="body">{rows}</div>
}
I wonder what could be causing this issue?
And how can I get the correct result also in Europe time zone?
I searched and found this thread - https://github.com/date-fns/date-fns/issues/376
and also tried with moment.js to see if it works correctly, but it was the same result with
moment.js
My guess now is that
a. how the Date object is created, and its UTC format is resulting different behaviour based on the time zone.
b. day value is day + 1, inside of the if(hasMatching) statement. And I wonder if this also effects how it renders the schedule element.
I am trying to compare the value of month number field month=6coming from my backend to the current month number. if the match is true 'do something' else do 'something else'.
I have tried making use of javascript Date() object and also moment():
var date = new Date();
var month = date.getMonth()+1;
Moment:
var month = moment().month("M");
This here is the function where the value of the current month is required
// get all Item usage on each item by month
const GroupedByMonth = Object.values(
data.reduce((acc, curr) => {
if (curr._id.month === month){
return (
(acc[curr._id.name] = {
month: curr._id.month,
name: curr._id.name,
totalAmountSold:
(acc[curr._id.name]?.totalAmountSold || 0) +
curr.totalAmountSold,
}),
acc
);
}
return acc;
}, {})
);
console.log(GroupedByMonth);
Object from backend :
{month: 6, name: "Cement", totalAmountSold: -17}
expected output should should read :
if (curr._id.month(6 coming from backend) === month(6 coming from date object){
in the case of true, the rest of the functions is performed
Non of the method i tried worked as expected. I need help in solving this problem
I don't quite understand what you mean by
Non of the method i tried worked as expected.
What have you tried so far? And what are the results?
That aside you can try something like this:
var today = new Date(); //Thu Jun 18 2020 10:17:04 GMT-0300
var month = ('0' + (today.getMonth() + 1)).slice(-2);
//Expected output of month: '06'
Make sure that what you are trying to compare matches in value and type, since you are using ===
function isDateMatched (monthNo) {
return new Date().getMonth() === monthNo;
}
console.log('5th month ', isDateMatched(5))
console.log('4th month ', isDateMatched(4))
Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
Date.getMonth() returns current month no.
You can simply pass the monthNo you get from backend & pass it to isDateMatched function, it will return a Boolean i.e, true/false
Based on this result you can do your work.
I'm working with eBay api and trying to turn the endTime field which is in a dateTime format into a field that shows how much time is left in an auction, such as 5 minutes or 5 hours or 5 days.
In node, i'm making call to eBay api and mapping the endTime field into a variable, using the moment function.
It looks like this:
var moment = require("moment");
moment().format();
const cardsData = newData.map(card => ({
timeLeft: moment(
card.listingInfo && card.listingInfo[0].endTime
).fromNow()
Every value in the loop is returning 'a year ago'.
This is what the actual endTime field looks like
endTime: [
"2019-12-25T18:37:33.000Z"
],
where am i going wrong? does this date need to be formatted somehow before I can use moment?
So turns out adding a new Date wrapper gets this working. But i'm not exactly sure why. If anyone has any input, would be happy to hear. Thanks
timeLeft: moment(
new Date(card.listingInfo && card.listingInfo[0].endTime)
).fromNow()
As #RobG pointed out, this is incorrect. Sorry.
The expression you pass to moment(card.listingInfo && card.listingInfo[0].endTime) is a boolean expression, evaluating to true or false. Instead, I would filter newData where card.listingInfo is valid like this:
newData = newData.filter(card => {
return card.listingInfo && card.listingInfo[0];
});
Then for map you would do:
newData.map(card => ({
timeLeft: moment(card.listingInfo[0])
})
i'm working ing a react js project and I'm using antd.design Library to show a RangePicker
what i'm trying to solve is how can i get the start date and the end date from this RangePicker when user select a period
that's my code :
handleChangeDebut =range => {
const valueOfInput1 = moment(range.startDate).format();
const valueOfInput2 = moment(range.endDate).format();
console.log('start date',valueOfInput1);
console.log("end date",valueOfInput2);
}
<DatePicker.RangePicker
style={{ width: "100%" }}
getPopupContainer={trigger => trigger.parentNode}
onChange={this.handleChangeDebut}
/>
the issue is on my handleChange function , i always get the date of the current day
is there any attributes in antd design that give us the startDate and the EndDate Selected ?
Thank you for your precious help .
From the documentation, this is the signature of the onChange function function(dates: moment, moment, dateStrings: string, string), It looks like start and end date are passed as an array in the first param:
handleChangeDebut = (range) => {
const valueOfInput1 = range[0].format();
const valueOfInput2 = range[1].format();
console.log('start date',valueOfInput1);
console.log("end date",valueOfInput2);
}
I am using material-ui v0.20.0 for React js
This is my DatePicker component
<Field
name='appointmentDate'
label="Select Date"
component={this.renderDatePicker}
/>
renderDatePicker = ({ input, label, meta: { touched, error }, ...custom,props }) => {
return (
<DatePicker
{...input}
{...custom}
autoOk={true}
floatingLabelText={label}
dateForm='MM/DD/YYYY'
shouldDisableDate={this.disabledDate}
minDate={ new Date()}
value={ input.value !== '' ? input.value : null }
onChange={(event, value) => input.onChange(value)}
/>
);
};
What should I write in disabledDate(){...} if I want to disable any of the day/s ?
Here is the sample code that needed to be added.
You can refer this link for more details - https://material-ui.com/components/pickers/#date-time-pickers
You can add condition according to your need in order to disable date.
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
function disableWeekends(date) {
return date.getDay() === 0 || date.getDay() === 6;
}
function disableRandomDates() {
return Math.random() > 0.7;
}
/**
* `DatePicker` can disable specific dates based on the return value of a callback.
*/
const DatePickerExampleDisableDates = () => (
<div>
<DatePicker hintText="Weekends Disabled" shouldDisableDate={disableWeekends} />
<DatePicker hintText="Random Dates Disabled" shouldDisableDate={disableRandomDates} />
</div>
);
export default DatePickerExampleDisableDates;
Consider this
above code code is cutted (demo code is inside a component)
disableWeekends(date) {
/* date interdites french format dd/mm for all year !
01/01
01/05
08/08
14/07
15/08
01/11
11/11
25/12
replace date.getFullYear() by the desired year otherwise
*/
// in the following array format is us month are starting from 0 till 11
const dateInterditesRaw = [
new Date(date.getFullYear(),0,1),
new Date(date.getFullYear(),4,1),
new Date(date.getFullYear(),7,8),
new Date(date.getFullYear(),6,14),
new Date(date.getFullYear(),7,15),
new Date(date.getFullYear(),10,1),
new Date(date.getFullYear(),10,11),
new Date(date.getFullYear(),11,25),
];
/* make a new array with the getTime() without it date comparaison are
never true */
const dateInterdites = dateInterditesRaw.map((arrVal) => {return
arrVal.getTime()});
/*exclude all sunday and use the includes array method to check if the
date.getTime() value is
in the array dateInterdites */
return date.getDay() === 0 || dateInterdites.includes(date.getTime());
}
render() {
return(
<DatePicker
floatingLabelText="Jour de la visite"
value={this.props.dateVisite}
shouldDisableDate={this.disableWeekends}
onChange={this.handleChangeDateVisit}
/>
);
}
}
in the updated API it's the "disablePast" property.
check https://material-ui-pickers.dev/api/DatePicker
I tried to filter the days I had as an array of days with the steps below:
converted strings into a Date object.
converted the Date objects into timeStamp for comparison.
compare timeStamps plus the weekends with all the dates we have in our calendar.
const disableBookedDays = (date) => {
const convertedIntoDateObject = bookedDates.map((bookedDate) => {
return new Date(bookedDate).getTime();
});
return date.getDay() === 0 || date.getDay() === 6 || convertedIntoDateObject.includes(date.getTime());
};
For specific day:
Example: disable May 03 2021
<DatePicker
shouldDisableDate={(date) => date.getTime() === new Date('2021-05-03T00:00').getTime()}
/>
const disabledDays = (date) => {
return !myDates.map((myDate) => new Date(myDate).getTime()).includes(date.getTime());
};
Para deshabilitar un array de fechas especificas
User or to add multiple specific dates
<DatePicker shouldDisableDate={(date) => date.getTime() === new Date('2021-05-03T00:00').getTime() || new Date('2021-05-04T00:00').getTime() || new Date('2021-05-05T00:00').getTime()}
/>