how to change the format of React DateTimePicker while displaying time on our webpage in react functional component

359 views Asked by At

I am new to react could you please through this.

Image of output of date and time If you see image I am getting output or is being displayed date and time as 2023-01-13T22:54:00.000Z. but I want to display the date and time in this format as 20 Jan,5:25 PM. <DateTimePicker onChange={(value)=>setValue(value)} value={value} /> const [value, setValue] = useState(new Date()); I have above for using dateTime picker. The another problem I am facing is when make onChange={e=>setValue(e.target.value)} when I am trying to select date I am getting blank page so I didn't use it. Sometimes in scenarios I am unable to pick date.

I want a date and time picker where a user can pick his own date and time but In a single input and save them and also to display on screen as per the format.

const [value, setValue] = useState(new Date());

const months = ["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"];

   `var day=value.getDate();
// let name = months[value.getMonth()];
// var string = day + ' ' + name;
// var hours=value.getHours();
// var minutes=value.getMinutes();
// var ampm = hours >= 12 ? 'PM' : 'AM';
// var string2 = hours + ':' + minutes + ' ' + ampm;
// const clock=string+','+string2;`

I tried this but it is displaying the current date and time and keeps updating as time changes. So I thought may be the value is not yet updated to see change in this.

  `<p><span style={{fontSize:12}}>{item.value}</span></p>`

I am using a mapping function in order display elements. I tried to add methods like getdate and getmonth in the above

tag but it is not working and I am getting a blank page.

could you please help me with this issue so that I can get the above format and display datetime which is picked by user only.

I also tried to use HTML date and time picker but I am unable to format to this 20 Jan,5:25 PM.

and the main feature I want is to be able to pick date and time through one input and display it in above mentioned format which is user picked one and do not update.

Could you please help me this.

1

There are 1 answers

0
Isuru Madusanka On

You can use moment.js to format data and time.

import moment from 'moment'

function MyApp() {
  const [value, setValue] = useState(new Date());

  return (
    <div>
      <DateTimePicker onChange={setValue} value={value} />

     <p><span style={{fontSize:12}}>{moment(value).format('d MMM,h:mm A')}</span></p>
   </div>
 );
}

Hope this will solve your problem. You can pass the format that you want as an argument to format function. You can find more details in here. https://momentjs.com/docs/#/displaying/