[英]date and time concatenate the values in react Js
how to concatenate the date and time value in react js. 如何在React JS中连接日期和时间值。 for date and time picking i am using material UI datepicker and timepicker for selecting the date and time this my example code.
对于日期和时间选择,我正在使用材料UI datepicker和timepicker选择示例代码中的日期和时间。
selectDate(event, date) {
this.setState({
updatedDate: moment(date).format('DD-MM-YYYY'),
});
}
selectTime(event, time) {
this.setState({
startime: moment(time).format('HH:mm')
});
}
i want to convert to YYYY-MM-DDThh:mm:ss
this format 我想转换为
YYYY-MM-DDThh:mm:ss
这种格式
If it really has to remain a datetime string in state at all times then something along these lines should work (ie taking the previous set state string, converting to a moment
object, modifying the relevant parts only, then applying back to state as a string again) 如果确实确实必须始终保持日期时间字符串处于状态,那么应该遵循这些原则(例如,使用先前设置的状态字符串,转换为
moment
对象,仅修改相关部分,然后以字符串形式应用于状态)再次)
format = 'YYYY-MM-DDThh:mm:ss'
selectDate = (event, date) => this.setState( d => prevState => ({
datetimeStr: (moment(prevState.datetimeStr, this.format) || d)
.year(d.year()).month(d.month()).date(d.date())
.format(this.format)
})(moment(date)))
selectTime = (event, time) => this.setState( d => prevState => ({
datetimeStr: (moment(prevState.datetimeStr, this.format) || d)
.hour(d.hour()).minutes(d.minutes())
.format(this.format)
})(moment(time)))
But would be far more flexible if they are both stored in state as actual Date objects and only combined/formatted when needed as a string in some output, that way if need to be formatted differently in different places you can still derive it from the same state 但是,如果它们都以状态形式存储为实际的Date对象,并且仅在需要时作为某些输出中的字符串进行组合/格式化,则将更加灵活,这样,如果需要在不同的位置进行不同的格式化,则仍然可以从同一位置派生它州
selectDate = (event, date) => this.setState({date})
selectTime = (event, time) => this.setState({time})
getSelectedDatetimeStr = () => {
const date = moment(this.state.date || {})
const time = moment(this.state.time || {})
return moment({
year: date.year(),
month: date.month(),
day: date.date(),
hours: time.hours(),
minute: time.minutes()
}).format('YYYY-MM-DDThh:mm:ss')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.