【问题标题】:Material-Ui DatePicker change to stringMaterial-Ui DatePicker 更改为字符串
【发布时间】:2017-07-05 05:49:59
【问题描述】:

有没有办法让 Material-UI DatePicker 的值为String 而不是Date Object?我只想为日期值设置 YYYY-MM-DD。现在我正在做的是在将其发送到服务器之前对其进行编辑。

【问题讨论】:

    标签: datepicker material-ui


    【解决方案1】:

    这是迄今为止我发现的最好的材料 ui datepicker。它允许用户键入和选择日期,还可以显示字符串值(也可以用作输入值)。希望对您有所帮助!

    import React, { PropTypes } from 'react';
    import TextField from 'material-ui/TextField';
    import DatePicker from 'material-ui/DatePicker';
    import Clear from 'material-ui/svg-icons/content/clear';
    import DateIcon from 'material-ui/svg-icons/action/date-range';
    import FontIcon from 'material-ui/FontIcon';
    import format from 'date-fns/format';
    import compose from 'recompose/compose';
    import withHandlers from 'recompose/withHandlers';
    import withState from 'recompose/withState';
    import moment from 'moment';
    
    const convertDateToYyyyMmDd = (date) => {
      if (!date) return '';
      return moment(date, 'DD/MM/YYYY').format('YYYY-MM-DD');
    };
    
    const enhance = compose(
      withState('stringValue', 'changeStringValue', props => {
        const { value } = props;
        if (value) return format(props.value, 'DD/MM/YYYY');
        return '';
      }),
      withState('valueOnFocus', 'changeValueOnFocus', ''),
      withHandlers({
        onChangeDatePicker: props => (event, val) => {
          props.input.onChange(
            format(val, 'YYYY-MM-DD')
          );
          props.changeStringValue(format(val, 'DD/MM/YYYY'));
        },
        onChange: props => (event, val) => props.changeStringValue(val),
        onBlur: props => event => {
          const { value } = event.target;
          if (value != props.valueOnFocus) {
            if (!value) {
              props.input.onChange(null);
              props.changeStringValue('');
            } else {
              const date = new Date(convertDateToYyyyMmDd(value));
              props.input.onChange(date);
              props.changeStringValue(format(date, 'DD/MM/YYYY'));
            }
          }
        },
        onFocus: props => () => props.changeValueOnFocus(props.value),
        clearDate: props => () => {
          props.input.onChange(null),
          props.changeStringValue('');
        }
      }),
    );
    
    class MyDatePicker extends React.Component {
    
      static propTypes = {
        input: PropTypes.object,
        mode: PropTypes.string,
        floatingLabelText: PropTypes.string,
        textFieldStyle: PropTypes.object,
        tree: PropTypes.Object,
        fieldName: PropTypes.string,
        value: PropTypes.string | PropTypes.number,
        stringValue: PropTypes.string | PropTypes.number,
        errorText: PropTypes.string,
        disabled: PropTypes.boolean,
        onChangeDatePicker: PropTypes.func,
        onChange: PropTypes.func,
        clearDate: PropTypes.func,
        onBlur: PropTypes.func,
        onFocus: PropTypes.func,
      }
    
      static defaultProps = {
        value: null,
        stringValue: '',
        errorText: '',
        disabled: false,
      }
    
      render() {
        const {
          errorText,
          disabled,
          onChangeDatePicker,
          onChange,
          onBlur,
          onFocus,
          clearDate,
          input,
          mode,
          floatingLabelText,
          textFieldStyle } = this.props;
    
        const stringValue = this.props.stringValue ? this.props.stringValue : input.value ? format(input.value, 'DD/MM/YYYY') : '';
        const valueDate = input.value ? new Date(input.value ) : {};
    
        return (
          <div className="P-date-field">
            <TextField
              floatingLabelText={floatingLabelText}
              type="text"
              value={stringValue || ''}
              errorText={errorText}
              disabled={disabled}
              fullWidth
              onChange={onChange}
              style={textFieldStyle}
              ref="datePicker"
              onBlur={onBlur}
              onFocus={onFocus}
            />
            <FontIcon
              id="iconCalendar"
              className="material-icons"
              title="Open calendar"
              onClick={!disabled ? () => this.datePicker.focus() : null}
            >
              <DateIcon />
            </FontIcon>
            <FontIcon
              style={disabled ? {display: 'none'} : ''}
              id="iconClear"
              className="material-icons"
              title="Clear date"
              onClick={clearDate}
            >
              <Clear />
            </FontIcon>
            <div className="datePicker-hidden">
              <DatePicker
                id="dataPicker"
                name={input.name}
                floatingLabelText={''}
                value={valueDate}
                errorText={errorText}
                disabled={disabled}
                DateTimeFormat={window.Intl.DateTimeFormat}
                locale="de-CH-1996"
                formatDate={v => format(v, 'DD/MM/YYYY')}
                mode={mode}
                autoOk={true}
                fullWidth
                cancelLabel="Cancel"
                onChange={onChangeDatePicker}
                ref={c => (this.datePicker = c)}
              />
            </div>
          </div>
        );
      }
    }
    
    export default enhance(MyDatePicker);

    【讨论】:

      【解决方案2】:

      Date Javascript 中的对象有一个原型函数可以将日期更改为字符串。

      var date = new Date();
      var abc = date.toString();
      
      console.log(abc); // Returns "Thu Feb 16 2017 12:01:19 GMT-0800 (PST)"
      

      如果您指的是如何在发送到服务器之前将日期更改为特定格式,您可以使用moment.js 使用类似的功能 moment(dateObject, 'YYYY-MM-DD')DatePicker 中提取dateObject 之后。

      这是一个快速的小提琴,显示了动作中的时刻格式化: http://jsfiddle.net/fjz56wgg/

      【讨论】:

      • 这就是我现在正在做的事情。我只是在寻找一种在提交之前而不是在组件方面进行更改的方法。
      • 是否有理由需要该值是字符串而不是组件本身中的日期对象?如果您查看 github 上 DatePicker 组件的源代码,组件中内置了一些函数,需要 value 属性是日期对象,例如 formatDate 函数。从组件中检索该值后,对其进行按摩要比将该值作为字符串进行任何修改要容易得多。 github.com/callemall/material-ui/blob/master/src/DatePicker/…
      • formatDate 函数只改变日期对象的外观。当您将它发送到服务器时,它仍然是日期对象。数据库需要 YYYY-MM-DD 格式的日期数据类型
      • 我猜你有一个 mySQL 数据库并且需要这种格式,对吗?您可以在将日期对象发送到服务器之前使用时刻将日期对象转换为 mySQL 的正确日期格式。我不明白为什么需要修改组件本身的值。 stackoverflow.com/questions/26047755/…formattedValue = moment(value).format("YYYY-MM-DD HH:mm:ss");
      • 想象数百个需要编辑的日期对象字段。现在想象一下编辑自己一个一个地定义它。您可以检查它是否是日期对象,但可以想象是否有一些字段需要日期时间。所以你不能真正拥有一切。唯一的方法是在组件本身上对其进行格式化
      猜你喜欢
      • 2021-08-27
      • 1970-01-01
      • 2019-07-31
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 2019-04-26
      相关资源
      最近更新 更多