简体   繁体   English

react-datepicker 不将 setState 设置为 dd/MM/yy

[英]react-datepicker doesn't setState to dd/MM/yy

The date is presented in the right format (31/08/21), but onChange sets the startDate to something like this:日期以正确的格式 (31/08/21) 显示,但 onChange 将 startDate 设置为如下所示:

Tue Aug 31 2021 21:29:17 GMT+0200 (Mitteleuropäische Sommerzeit) 2021 年 8 月 31 日星期二 21:29:17 GMT+0200(Mitteleuropäische Sommerzeit)

How can I save the format I display?如何保存我显示的格式?

import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function Bodyweight() {
  
const [startDate, setStartDate] = useState(new Date());

return(
<div>
  <DatePicker
          dateFormat="dd/MM/yy"
          selected={startDate}
          onChange={(date) => setStartDate(date)}
        />
</div>
)}

Your DatePicker component accepts date in Tue Aug 31 2021 21:29:17 GMT+0200 (Mitteleuropäische Sommerzeit) format.您的DatePicker组件接受Tue Aug 31 2021 21:29:17 GMT+0200 (Mitteleuropäische Sommerzeit)格式的日期。

And it also returns the date in same format.它还以相同的格式返回日期。

In order to convert the date in required format, you have few options.为了将日期转换为所需格式,您有几个选择。

  1. If DatePicker is your own component, check its implementation and modify the code, so that it returns the date in required format.如果 DatePicker 是您自己的组件,请检查其实现并修改代码,使其以所需格式返回日期。

  2. If option 1 is not an option, then manually convert the date in required format.如果选项 1 不是一个选项,则手动将日期转换为所需格式。 Note that you may need a third variable to store the formatted date, as your DatePicker components accepts an actual date object not string.请注意,您可能需要第三个变量来存储格式化日期,因为您的 DatePicker 组件接受实际日期 object 而不是字符串。

Refer this link to convert date in req format.请参考此链接以请求格式转换日期。 Format JavaScript date as yyyy-mm-dd 格式 JavaScript 日期为 yyyy-mm-dd

Just use new Date().toLocaleDateString() in your initial state set, ie,只需在初始 state 集中使用new Date().toLocaleDateString()即可,即

const [startDate, setStartDate] = useState(new Date().toLocaleDateString());

I'm answering according to my understanding, if this is not the solution you are looking for, please do rectify in comments我是根据我的理解来回答的,如果这不是你要找的解决方案,请在评论中纠正

A bit late to the party but you could try something like this onChange={(date:Date) => setStartDate(date)}派对有点晚了,但你可以试试这样的onChange={(date:Date) => setStartDate(date)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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