最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change date format of DatePicker in React - Stack Overflow

programmeradmin1浏览0评论

I am just trying to display a date from the DatePicker ponent in React but it displays it as an Object :

startDateOwner: Mon Feb 08 2021 00:00:00 GMT+0100 (Central European Standard Time)

How could I display it as 08/02/2021 and as a string?

Here is the code I am using:

const Calendar = ({ startDate, endDate, handleChangeDates }) => (
  <div>
    <label> Beginning date
    <DatePicker 
      name = "startDate"
      selected={startDate}
      selectsStart
      startDate={startDate}
      endDate={endDate}
      onChange={(date)=>handleChangeDates(date, "startDate")}
    />
    </label>
    <label> End date
    <DatePicker
      name = "endDate"
      selected={endDate}
      selectsEnd
      startDate={startDate}
      endDate={endDate}
      minDate={startDate}
      onChange={(date)=>handleChangeDates(date, "endDate")}
    />
    </label>
  </div>

I am just trying to display a date from the DatePicker ponent in React but it displays it as an Object :

startDateOwner: Mon Feb 08 2021 00:00:00 GMT+0100 (Central European Standard Time)

How could I display it as 08/02/2021 and as a string?

Here is the code I am using:

const Calendar = ({ startDate, endDate, handleChangeDates }) => (
  <div>
    <label> Beginning date
    <DatePicker 
      name = "startDate"
      selected={startDate}
      selectsStart
      startDate={startDate}
      endDate={endDate}
      onChange={(date)=>handleChangeDates(date, "startDate")}
    />
    </label>
    <label> End date
    <DatePicker
      name = "endDate"
      selected={endDate}
      selectsEnd
      startDate={startDate}
      endDate={endDate}
      minDate={startDate}
      onChange={(date)=>handleChangeDates(date, "endDate")}
    />
    </label>
  </div>

Thank you ! Julie

Share Improve this question asked Feb 9, 2021 at 8:30 djou0501djou0501 471 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

React date picker provides a attribute dateFormat

<DatePicker 
      name = "startDate"
      selected={startDate}
      selectsStart
      startDate={startDate}
      endDate={endDate}
      onChange={(date)=>handleChangeDates(formatDateFn(date), "startDate")}
      dateFormat="dd/MM/YYYY"  (Use dd/MM/yyyy  if you get error in console)
    />


const formatDateFn = (date) => {
     const selectedDate = new Date(date)
     return selectedDate.getDate() + "/"+ parseInt(selectedDate.getMonth()+1) +"/"+ selectedDate.getFullYear();

} 

You are wele! Subodh

If you're objective is to just display the date in (dd/mm/yyyy) format, you may use moment

moment(date_variable).format("DD/MM/YYYY")

This would work to display date.

发布评论

评论列表(0)

  1. 暂无评论