[英]React compare or match two dates
I am facing an issue in React JS.我在 React JS 中遇到了一个问题。 I want to do compare or match the start_date
with header date
我想将start_date
与header date
进行比较或匹配
Rest API Rest API
[
{
"id": "1",
"staff_name": "Jill",
"custom_service_name": "Jone",
"start_date": "2020-05-06 11:30:00",
"end_date": "2020-05-06 11:45:00",
},
{
"id": "2",
"staff_name": "james",
"custom_service_name": "smith",
"start_date": "2020-05-06 11:00:00",
"end_date": "2020-05-06 11:15:00",
}
]
console.log data: console.log 数据:
1:00 AM //start_date
["9:43:36 AM", "9:13:36 AM", "10:13:36 AM"] //header_date
12:00 PM
["9:43:36 AM", "9:13:36 AM", "10:13:36 AM"] //header_date
2:15 AM
["9:43:36 AM", "9:13:36 AM", "10:13:36 AM"] //header_date
My Code:我的代码:
var currentdate = new Date(); //header_date logic
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
var current = currentdate.toLocaleTimeString();
var previous = prevdate.toLocaleTimeString();
var first = firstdate.toLocaleTimeString();
var headerdate = [previous ,current, first];
this.state = {
headerdate:headerdate,
appointmentdata:[]
}
componentDidMount() { //get start_date
axios.get(`http://localhost/route/v1/appointment`)
.then(res => {
const appointmentdata = res.data;
console.log(appointmentdata);
this.setState({ appointmentdata });
})
}
I try, but this logic is not working我尝试,但这个逻辑不工作
render() { return (
<div>
{this.state.appointmentdata.map(data =>
{ const dateTime = moment(data.start_date.toString());
if (dateTime.format("h:mm A") === this.state.headerdate)
{
return <p>{dateTime.format("h:mm A")}</p>; } //return the match date
else { return null; } })}
Demo:演示:
https://codesandbox.io/s/quizzical-browser-9e3g4 https://codesandbox.io/s/quizzical-browser-9e3g4
What should i do?我应该怎么办? Can anyone help me谁能帮我
I see you're using Moment.我看到你正在使用 Moment。 So you can use isSame
built-in helper from them to achieve this.因此,您可以使用他们提供的isSame
内置助手来实现此目的。
Docs: https://momentjs.com/docs/#/query/is-same/文档: https://momentjs.com/docs/#/query/is-same/
Example code:示例代码:
const isSameDate = (start_date, header_date) => {
const startDate = moment(start_date);
const headerDate = moment(header_date);
return startDate.isSame(headerDate, 'day');
}
One small tip, you should move the date checking outside the render
method, that would makes your code easier to read and maintainable一个小技巧,您应该将日期检查移到render
方法之外,这将使您的代码更易于阅读和维护
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.