简体   繁体   中英

How to default to current UTC date/time for Material UI date time picker

I'm trying to create a dialog for the user to provide start and end date/time with React and Material UI. I'd like to default the start to the beginning of the current day and the end to the end of the current day (UTC), but I can't even figure out how to get a default date and time to show up.

I have the start and end in the state like this:

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

and then I have the fields in the render method:

<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}
/>

but when I open the dialog, the text fields have mm/dd/yyyy --:-- -- instead of the current date/time set up in the state. I've tried both toUTCString and toString to provide the date using defaultValue or value, but nothing is working...

I'd like the current UTC date to show up in the text fields.

this is what I ended up with:

                    <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}
                    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM