简体   繁体   English

在 React 中使用 moment.js 格式化日期的问题

[英]Problems with formatting date with moment.js in React

I was creating weather app in React by using Open Weather Map API and as you know, API gives us data on 5 day/3 hour forecast.我正在使用 Open Weather Map API 在 React 中创建天气应用程序,如您所知,API 为我们提供了 5 天/3 小时预报的数据。 Moreover, since API by default uses a GMT Unix timestamp format I decided to format it into "MM-DD-YYYY" to work with date easily.此外,由于 API 默认使用 GMT Unix 时间戳格式,因此我决定将其格式化为“MM-DD-YYYY”以便轻松处理日期。 But the problem is when I try to further convert "MM-DD-YYYY" into LT format in moment.js I lose time date in date and by default all time gets 12:00 AM.但问题是当我尝试在 moment.js 中进一步将“MM-DD-YYYY”转换为 LT 格式时,我丢失了 date 中的时间日期,默认情况下所有时间都为 12:00 AM。 Is it true that if we try to convert original GMT Unix timestamp format into "MM-DD-YYYY" and then further convert "MM-DD-YYYY" into "LT" we will lose time that was in GMT Unix timestamp?如果我们尝试将原始 GMT Unix 时间戳格式转换为“MM-DD-YYYY”,然后进一步将“MM-DD-YYYY”转换为“LT”,我们是否会丢失 GMT Unix 时间戳中的时间?

在此处输入图像描述

import React, { Fragment, Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import SearchBox from "./Containers/SearchBox/SearchBox";
import Header from "./Components/Header/Header";
import styles from "./App.module.css";
import CardContainer from "./Containers/CardContainer/CardContainer";
import Footer from "./Components/Footer/Footer";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import About from "./Components/About/About";
import axios from "axios";
import WeatherDay from "./Components/WeatherDay/WeatherDay";
class App extends Component {
  state = {
    title: null
  };

  getTitle = location => {
    axios
      .get(
        `http://api.openweathermap.org/data/2.5/forecast?q=${location}&APPID=7ad09d078633b652ecef8587a337639e&units=metric`
      )
      .then(res => {
        this.setState({
          title: res
        });
      })
      .catch(err => {
        console.log(err);
      });
  };

  render() {
    return (
      <Router>
        <div className={styles.App}>
          <Fragment>
            <Header title={"Weather App"} />
            <Switch>
              <Route
                path="/"
                exact
                render={props => (
                  <Fragment>
                    <div className="container">
                      <SearchBox getRequest={this.getTitle} />
                    </div>
                    <main className={styles.mainContent}>
                      <h1 className={styles.cityWeather}>
                        {this.state.title && this.state.title.data.city.name}
                      </h1>
                      <CardContainer
                        weatherData={
                          this.state.title && this.state.title.data.list
                        }
                      />
                    </main>
                  </Fragment>
                )}
              />

              <Route path="/about" component={About} />
              <Route
                path="/day/:date"
                render={props => (
                  <WeatherDay {...props} title={this.state.title} />
                )}
              />
            </Switch>
            <Footer copyright={"Copyright 2018"} />
          </Fragment>
        </div>
      </Router>
    );
  }
}

export default App;


import React from "react";
import "./WeatherDay.module.css";
import moment from "moment";
const WeatherDay = props => { // This is the component where I have a problem with conversion
  const allDays =
    props.title &&
    props.title.data.list.map(item => ({
      date: moment(new Date(item.dt_txt)).format("MM-DD-YYYY"),
      main: item.main,
      weather: item.weather
    }));
  const chosenDate = props.match.params.date;

  const day =
    props.title &&
    allDays.filter((item, index) => {
      return item.date === chosenDate;
    });

  const mir =
    props.title &&
    day.map(item => { //Here I am trying to convert "MM/DD/YYYY" into "LT" and lose time info
      return <p>{moment(new Date(item.date)).format("LT")}</p>;
    });

  return (
    <div className="row">
      <div className="col-md-2"></div>
      {mir}
            </div>
          );
        })}
    </div>
  );
};

export default WeatherDay;

在此处输入图像描述

I think you mixed up sth.我觉得你搞混了。 here.这里。 You should not use a time string to actually calculate it, only change the format for your date, but keep the actual moment object for further calculations.您不应该使用时间字符串来实际计算它,只需更改日期的格式,而是保留实际时刻 object 以进行进一步计算。 This way you always have the right time and dates.这样,您总是有正确的时间和日期。

I think you formatting on already formatted date.我认为您在已格式化的日期上进行格式化。 You should sustain the moment object instead of formatted date.您应该坚持使用 object 而不是格式化日期。

You should format the date only at the time of rendering.您应该仅在渲染时格式化日期。 While passing we pass moment object.在传递的同时,我们传递了moment object。

Example例子

let parsed = moment(new Date())
let format1 = parsed.format('MM-DD-YYYY')
let format2 = parsed.format('LT')
console.log(format1) // 09-20-2019
console.log(format2) // 3:43 PM

Hope that helps!!!希望有帮助!!!

I think the problem is due to this,我认为问题是由于这个,

date: moment(new Date(item.dt_txt)).format("MM-DD-YYYY")

When you convert date as above it strips out time from it and you get simple date.当您如上所述转换日期时,它会从中删除时间,您会得到简单的日期。

It should be this,应该是这样

date: moment(new Date(item.dt_txt)).format("MM-DD-YYYY, h:mm:ss a")

Demo演示

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

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