简体   繁体   English

反应日期选择器和时刻

[英]React Date Picker and Moment

Good evening everyone, I'm kinda having issue with react date picker and moment.大家晚上好,我对反应日期选择器和时刻有点问题。 I've formatted the date and moment still I'm getting a UTC error.我已经格式化了日期和时刻,但仍然收到 UTC 错误。 Even though my props is showing and the children are getting initialize from the parent the date still in a wrong a format and the API I"m getting the data from is using YYYY-MM-DD format of date.即使我的道具正在显示并且孩子们正在从父母那里初始化日期仍然是错误的格式,而且我从中获取数据的 API 正在使用YYYY-MM-DD格式的日期。

I've done all I know about date and time formatting both with moment and react date picker.我已经用时刻和反应日期选择器完成了我所知道的关于日期和时间格式的所有工作。 When I use ordinary form everything works fine but the date picker is having issue..I can fetch data without no issue.当我使用普通表单时,一切正常,但日期选择器有问题..我可以毫无问题地获取数据。 I want the user to be able to choose a different date with the app or choose at random.我希望用户能够使用应用程序选择不同的日期或随机选择。 I've attached some screenshot for more clarity.为了更清楚,我附上了一些屏幕截图。 Thanks.谢谢。

        import React, { useState, useEffect } from "react";
        import axios from "axios";
        // import "./App.css";
        import moment from "moment";
        import styled from "styled-components";
        import DatePicker from "react-datepicker";
        import DisplayImg from "./components/DisplayImg"


        const ApodImg = styled.div`
        display:flex;
        object-fit:scale;
        padding-top 1rem;
        margin-bottom:1rem;
        width:80%;
        `;

        function App() {
          const [nasa, setNasa] = useState([]);

          const [curDate, setCurDate] = useState("")

          //  function changeDate(e) {[enter image description here][1]
          //   //disable button to avoid spamming
          //   e.target.setAttribute('disabled', true);
          //   //sets the value of what was picked on the input
          //   setCurDate(e.target.value);


          //  }

          // let newDate = new Date()
          // let year = newDate.getFullYear().toString()
          // let month = (newDate.getMonth() + 1).toString().padStart(2, '0')
          // let day = newDate.getDate().toString()
          // //format for api use, needs 2 digit month and day always
          // let formattedDate = `${year}-${month.padStart(2, '0')}-${day.padStart(
          //    2,
          //    '0'
          // )}`


          function change(e) {
            // disable button to avoid spamming
            e.target.setAttribute('disabled', true);
            // sets the value of what was picked on the input
            setCurDate(e.target.value);
          }

          // grabbing new (current) date
          let newDate = new Date()
          // grabbing the year from newDate above this
          let year = newDate.getFullYear().toString()
          // grabbing month from newDate adding 1 because JS numbers start at 0
          // turning it into a string. padStart places a 0 in front of the month since the current month is 1 digit
          let month = (newDate.getMonth() + 1).toString().padStart(2, '0')
          // grabbing day from newDate and turning it into a string
          let day = newDate.getDate().toString()
          //format for api to use, needs 2 digit month and day always (YYYY-MM-DD)
          let formattedDate = `${year}-${month.padStart(2, '0')}-${day.padStart(
            2,
            '0'
          )}`

          // setting setStartDate to formattedDate.toString()
          const [startDate, setStartDate] = useState(formattedDate.toString());

          useEffect(() => {
            const fetchData = () => {

            axios.get(`https://api.nasa.gov/planetary/apod?api_key=SJhTpR8dpNuNDns5czrQKr4iLMWoNA6hEkKEtO1j`)
              .then(res => {
                // setNasa(res.data)

                console.log(res)
              })

              .catch(error => {
                console.log("the data was requested", error)
              })

            }
            fetchData()

          }, [])

          useEffect(() => {
            const getPhoto = date => {
              axios.get(`https://api.nasa.gov/planetary/apod?api_key=SJhTpR8dpNuNDns5czrQKr4iLMWoNA6hEkKEtO1j&date=${startDate}`)

                .then(response => {
                  console.log(response)
                })

                .catch(error => {
                  console.log("The data was requested", error)
                })

            }
          }, [formattedDate])




          return (
            <ApodImg >

              <DatePicker selected={startDate} title='Pick a Date to View Another Image' onChange={e => change(e)} type='date' />
              <DisplayImg data={nasa} />
            </ApodImg>
          );
        }

        export default App;

Use the moment API to convert the date picker output to the format you need.使用 moment API 将日期选择器输出转换为您需要的格式。

Like this: moment(date, 'DD/MM/YYYY').format('YYYY-MM-DD')像这样:moment(date, 'DD/MM/YYYY').format('YYYY-MM-DD')

can use datepicker format as well也可以使用日期选择器格式


 <DatePicker format={"DD/MM/YYYY"} value={this.state.date}  onChange={this.onChange}/>

If you want to convert the date inside function can use below code如果你想在函数内部转换日期可以使用下面的代码

 let formatedDate = moment(this.state.date).format('YYYY-MM-DD');

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

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