Dha*_*val 4 javascript date momentjs reactjs react-redux
我正在使用 material-ui 日期选择器字段实现 redux-form。日期在字段中完美设置,但是当我尝试将其发送到日期的后端 API 格式时:
BeginDate_1: Tue Nov 14 2017 15:03:43 GMT+0530 (IST)
我正在尝试将此格式更改为“YYYY-mm-dd”格式,然后再将其发送到后端 API。
我尝试momentjs格式化,但无法得到我想要的结果。
这是我尝试过的:
主页.js
import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';
import DatePicker from 'material-ui/DatePicker';
import {connect} from 'react-redux';
import * as moment from 'moment';
class Home extends Component {
renderCalendarField= ({
input,
label,
meta: {touched, error},
children,
...custom
}) => (
<DatePicker
floatingLabelText={label}
errorText={touched && error}
{...input}
value = {input.value !== ''? new Date(input.value) : null}
onChange={(event, value) => input.onChange(value)}
children={children}
{...custom}
formatDate={(date) => moment(date).format('YYYY-MM-DD')}
/>
)
render() {
const startDate = new Date();
const {handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<div>
<Field name="BeginDate_1" component={this.renderCalendarField} label="DEPARTURE" minDate={startDate} />
</div>
<div>
<button type="submit">
Submit
</button>
</div>
</form>
);
}
}
const LogInForm = reduxForm({
form: 'MaterialUiForm', // a unique identifier for this form
validate
})(Home);
export default connect(mapStateTOProps, {getCity})(LogInForm);
Run Code Online (Sandbox Code Playgroud)
控制台输出仍然是:
BeginDate_1:Tue Nov 14 2017 15:03:43 GMT+0530 (IST)
如何以YYYY-mm-dd格式格式化此日期?
formatDate在支架DatePicker是用来format在Display Date,而不是实际值。您需要做的是,使用格式化onSubmit函数中的值moment
onSubmit (values) {
const beginDate = moment(values.BeginDate_1).format('YYYY-MM-DD')
console.log(beginDate);
//other things
}
Run Code Online (Sandbox Code Playgroud)
格式日期:函数
调用此函数以格式化输入字段中显示的日期,并应返回一个字符串。默认情况下,如果没有提供语言环境和 DateTimeFormat,则日期对象将被格式化为
ISO 8601 YYYY-MM-DD.签名:
Run Code Online (Sandbox Code Playgroud)function(date: object) => any date: Date object to be formatted. returns (any): The formatted date.
| 归档时间: |
|
| 查看次数: |
15010 次 |
| 最近记录: |