简体   繁体   English

Gatsby - 从 GraphQL 查询中获得的日期字段中提取日期和月份

[英]Gatsby - extracting day and month from date field obtained in GraphQL query

I'm a newbie web developer working with Gatsby, React, GraphQL and Javascript.我是一名新手 web 开发人员,与 Gatsby、React、GraphQL 和 Javascript 合作。 I'm working on a simple blog site in which I have some markdown posts whose frontmatter dynamically populate a list of blogposts on a page.我正在一个简单的博客网站上工作,其中有一些 markdown 帖子,其前端动态填充页面上的博客帖子列表。 I've managed to get this working so far but I wondered how one can work with data obtained from a graphQL query.到目前为止,我已经成功地完成了这项工作,但我想知道如何处理从 graphQL 查询中获得的数据。 I'd like to display just the day and month of the post in a stylised way as shown below:我想以一种风格化的方式显示帖子的日期和月份,如下所示:

程式化的日期

I'm using the following code to pull through the date of the markdown posts:我正在使用以下代码来查看 markdown 帖子的日期:

    const data = useStaticQuery(graphql`
    query{
        allMarkdownRemark{
        edges{
          node{
            frontmatter{
              title
              date
              featuredImage{
                  childImageSharp{
                      fluid{
                        ...GatsbyImageSharpFluid
                      }
                  }
              }
            }
            fields{
                slug
              }
          }
        }
      }
    }
    `)

  return(
        <div id="blog">
            <div class="blog-pad"></div>
            <div class="blog-posts">
            
                {data.allMarkdownRemark.edges.map((edge) =>(
                    <div class="blog-post">
                        <Img fluid={edge.node.frontmatter.featuredImage.childImageSharp.fluid} />
                        <div class="meta">
                            <h3>
                                {edge.node.frontmatter.date}
                            </h3> 
                            <div class="title-date">
                                <h3>
                                    <a href={"/blog/" + edge.node.fields.slug}>{edge.node.frontmatter.title}</a>
                                </h3> 
                                <p>{edge.node.frontmatter.date}</p>  
                                <p>Author</p>  
                            </div>
                        </div>    
                        </div>
                ))}
           
            </div>
            <div class="blog-pad"></div>
        </div>
    )

With a bit of styling added this results in:添加了一些样式后,结果如下:

我的清单

How can I extract just the day and month from this {edge.node.frontmatter.date} ?我怎样才能从这个{edge.node.frontmatter.date}中提取日期和月份? I thought to write a javascript function to do some string formatting on it however I'm not quite sure how to go about writing the function nor how it fits into the context of jsx and graphQL. I thought to write a javascript function to do some string formatting on it however I'm not quite sure how to go about writing the function nor how it fits into the context of jsx and graphQL. Would this query called const data get passed as a parameter to the function which would then return a string?这个名为const data的查询是否会作为参数传递给 function ,然后它会返回一个字符串? return <p>3 Dec</p>返回<p>3 Dec</p>

You have multiple approaches to achieve this:您有多种方法可以实现这一目标:

  • Gatsby uses momentjs to format dates on the fly in the GraphQL query using formatString : Gatsby 使用momentjsGraphQL 查询中使用formatString动态格式化日期:

     const data = useStaticQuery(graphql` query{ allMarkdownRemark{ edges{ node{ frontmatter{ title date(formatString: "YYYY.MM.DD") featuredImage{ childImageSharp{ fluid{...GatsbyImageSharpFluid } } } } fields{ slug } } } } } `)

    You can check for further formatting details in the momentjs docs .您可以在momentjs docs中查看更多格式细节。

  • If the previous approach doesn't fit your requeriments, you can always format the result using JavaScript + momentjs from the GraphQL response:如果以前的方法不符合您的要求,您始终可以使用 JavaScript + momentjs从 GraphQL 响应中格式化结果:

     const data = useStaticQuery(graphql` query{ allMarkdownRemark{ edges{ node{ frontmatter{ title date featuredImage{ childImageSharp{ fluid{...GatsbyImageSharpFluid } } } } fields{ slug } } } } } `) const formattedDate= date =>{ let day, month, year; day= moment(date).format("DD"); month= moment(date).format("MM"); year= moment(date).format("YYYY"); return <div>`${year}.${month}.${day}`</div> } return( <div id="blog"> <div class="blog-pad"></div> <div class="blog-posts"> {data.allMarkdownRemark.edges.map((edge) =>( <div class="blog-post"> <Img fluid={edge.node.frontmatter.featuredImage.childImageSharp.fluid} /> <div class="meta"> <h3> {formattedDate(edge.node.frontmatter.date)} </h3> <div class="title-date"> <h3> <a href={"/blog/" + edge.node.fields.slug}>{edge.node.frontmatter.title}</a> </h3> <p>{edge.node.frontmatter.date}</p> <p>Author</p> </div> </div> </div> ))} </div> <div class="blog-pad"></div> </div> )

You can format any date with the desired format using moment(yourDateHere).format(yourFormatHere) .您可以使用moment(yourDateHere).format(yourFormatHere)将任何日期格式化为所需的格式。 Using this approach you will be able to customize more the output and styling, adding HTML tags or removing spaces between dates.使用这种方法,您将能够自定义更多 output 和样式,添加 HTML 标签或删除日期之间的空格。

This can be done by defining a function which does simple string formatting outside of your JSX.这可以通过定义一个 function 来完成,它在 JSX 之外进行简单的字符串格式化。 You can then call your function in the curly brases {myFunction(parameter)} passing the graphQL query data to this function as a parameter.然后,您可以在花括号{myFunction(parameter)}中调用 function,将 graphQL 查询数据作为参数传递给此 function。

function dayMonth(data){

    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    //split up the string to get the day and month                    
    var month = parseInt(data.slice(5,7));
    var day = data.slice(8,10);

    //remove 0 from 02, 03 etc ... until 10
    if(day[0]=="0"){
        day = day.slice(1,2);
    }

    //concatenate the two together again and return
    var formatted = day + " " + monthNames[month];

    return formatted;
}

const BlogPage = () =>{

    const data = useStaticQuery(graphql`
    query{
        allMarkdownRemark{
        edges{
          node{
            frontmatter{
              title
              date
              featuredImage{
                  childImageSharp{
                      fluid{
                        ...GatsbyImageSharpFluid
                      }
                  }
              }
            }
            fields{
                slug
              }
          }
        }
      }
    }
    `);

    return(
        <div id="blog">
            <div class="blog-pad"></div>
            <div class="blog-posts">
            
                {data.allMarkdownRemark.edges.map((edge) =>(
                    <div class="blog-post">
                        <Img fluid={edge.node.frontmatter.featuredImage.childImageSharp.fluid} />
                        <div class="meta">
                                <h3>
                                {dayMonth(edge.node.frontmatter.date)}
                                </h3>
                            <div class="title-date">
                                <h3>
                                    <a href={"/blog/" + edge.node.fields.slug}>{edge.node.frontmatter.title}</a>
                                </h3> 
                                <p>{edge.node.frontmatter.date}</p>  
                                <p>Author</p>  
                            </div>
                        </div>    
                        </div>
                ))}
           
            </div>
            <div class="blog-pad"></div>
        </div>
    )
}  

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

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