如何为Material UI日期时间选择器默认设置为当前UTC日期/时间

时间:2019-04-16 06:13:55

标签: javascript reactjs material-ui

我正在尝试为用户创建一个对话框,以使用React和Material UI提供开始和结束日期/时间。我想将开始时间默认为当天的开始,将结束时间设置为当天的结束(UTC),但是我什至无法弄清楚如何获得默认的日期和时间来显示。 / p>

我在这样的状态下有起点和终点:

state = {
    start: new Date(),
    end: new Date()
};

然后在render方法中有字段:

<TextField
    type="datetime-local"
    label="Start Date/Time"
    InputLabelProps={{
        shrink: true
    }}
    required={true}
    // TODO make it start of today
    defaultValue={this.state.start.toUTCString()}
    onChange={this.handleStartChange}
/>
<TextField
    type="datetime-local"
    label="End Date/Time"
    InputLabelProps={{
        shrink: true
    }}
    required={true}
    value={this.state.end.toString()}
    // TODO make it end of today
    onChange={this.handleEndChange}
/>

但是当我打开对话框时,文本字段包含mm/dd/yyyy --:-- -- 而不是状态中设置的当前日期/时间。我已经尝试过toUTCString和toString使用defaultValue或value提供日期,但是没有任何作用...

我希望当前UTC日期显示在文本字段中。

1 个答案:

答案 0 :(得分:0)

这就是我最终得到的:

                    <TextField
                        style={{ margin: 0, width: '200px' }}
                        label="Start Date/Time (UTC)"
                        type="datetime-local"
                        defaultValue={this.state.start
                            .toISOString()
                            .slice(0, 16)}
                        InputLabelProps={{
                            shrink: true
                        }}
                        required={true}
                        onChange={this.handleStartChange}
                    />
                    <TextField
                        style={{ margin: 0, width: '200px' }}
                        label="End Date/Time (UTC)"
                        type="datetime-local"
                        defaultValue={this.state.end
                            .toISOString()
                            .slice(0, 16)}
                        InputLabelProps={{
                            shrink: true
                        }}
                        required={true}
                        onChange={this.handleEndChange}
                    />
相关问题