0

I am using Material-UI and this is their example code.

However I need the defaultValue to be today's current date and time; how can I go about this?

<TextField
    id="datetime-local"
    label="Next appointment"
    type="datetime-local"
    defaultValue="2017-05-24T10:30"
    className={classes.textField}
    InputLabelProps={{'
      shrink: true,
    }}
  />

I have tried to use something like this, however the issue is if month and day are 1-9 then how single digits and not double digits which means it won't set.

const currentdate = new Date(); 

  const datenow = currentdate.getFullYear() + "-"
                  + (currentdate.getMonth()+1)  + "-" 
                  + currentdate.getDay() + "T"  
                  + currentdate.getHours() + ":"  
                  + currentdate.getMinutes();
  
halfer
  • 19,824
  • 17
  • 99
  • 186
RussellHarrower
  • 6,470
  • 21
  • 102
  • 204

1 Answers1

1

You could do something like this.

  const d = new Date(); 
  const year = (d.getFullYear()).toString();
  const month = ((d.getMonth()) + 101).toString().slice(-2);
  const date = ((d.getDate()) + 100).toString().slice(-2);

  const hours = ((d.getHours()) + 100).toString().slice(-2);
  const mins = ((d.getMinutes()) + 100).toString().slice(-2);

  const datenow = `${year}-${month}-${date}T${hours}:${mins}`;
Sohaib
  • 10,941
  • 9
  • 32
  • 34