简体   繁体   中英

Formatting date and time using Moment with React JS

I'm new into coding and I'm trying to format date as DD/MM/YYYY and time as HH:MM using React Moment. I tried many methods with no success. It would be great if anyone could help me with this issue, as I'm still learning the basics.

How am I supposed to format {props.date} and {props.time} to make it more user-friendly?

Here's the code that I have:

import React, { Component } from "react";
import CreatedAtShow from "./CreatedAtShow";
import { Opportunities } from "../requests";
import { OpportunityShowPage } from "./OpportunityShowPage";
import moment from "react-moment";

function OpportunityDetails(props) {
  return (
        <div>
              <h2>
                  Opportunity: <br />
                  {props.title}
              </h2>
              <p></p>
              <h3>
                  Description: <br />
                  {props.description}
              </h3>
              
              <p>Tag:{props.tags}</p>
              <p>Date:{props.date}</p>
              <p>Time: {props.time}</p>
              <p>Where: {props.where}</p>
              <p>Contact information: {props.contact}</p>
              <p><CreatedAtShow created_at={props.created_at} /></p>    
  
              <button className="ui button"
                onClick={() => {
                    props.editOpportunity(props.id);
                }}
                > 
                Edit 
              </button>

              <button className="ui button"
              
                  onClick={() => props.deleteOpportunity(props.id)
                    // props.deleteOpportunity(props.id);
                  }> 
                  Delete 
              </button>
        </div>
  );
}

export default OpportunityDetails;

you can use momement js format function like this to get the desired part from date. If you can provide me some sample inputs and desired outputs then i can give you the exact answer. If you want to use with official moment.js npm then use below code.

If you want to get date and time from existing date then you can follow this:

<p>Date:{moment(props.date).format("DD/MM/YYYY"}</p>
<p>Time:{moment(props.time).format("HH:MM")}</p>

If you want today's or system date to be displayed then you can use:

<p>Date:{moment().format("DD/MM/YYYY"}</p>
<p>Time:{moment().format("HH:MM")}</p>

If you want to use react-moment then you can try this:

<p>Date:<Moment format="DD/MM/YYYY">{props.date}</Moment></p>
<p>Time:<Moment format="HH:MM">{props.time}</Moment></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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