【问题标题】:Vue JS - Retrieve date onlyVue JS - 仅检索日期
【发布时间】:2021-02-18 12:26:08
【问题描述】:

我正在进行一个检索一组对象的 api 调用。其中一个对象返回日期和时间,如下所示:

createdAt: "2020-11-04 09:48:32"

这是我显示日期和时间的地方:

<template v-for="item in collectedTrash">
        <BeforeAndAfter v-if="item.isPresented === 1"                            
                        :key="item.username"
                        :avatarUrl="require('@/assets/img/images/img_stats_km@2x.png')"
                        :imageBefore="getImageUrl(item.imageUrlBefore)"
                        :imageAfter="getImageUrl(item.imageUrlBefore)"
                        :username="item.username"
                        :date="item.createdAt"/> This is where I get the date
</template>

无论如何我只能检索日期,而不是日期和时间?

【问题讨论】:

    标签: javascript json vue.js date


    【解决方案1】:

    我假设您无权访问 api,因此必须在您的 vue 应用程序中处理日期。

    您需要将日期作为日期对象还是字符串? 如果字符串表示就足够了,您可以使用诸如Date fns 之类的库并使用格式函数:

    ...
    :date="format(new Date(item.createdAt), 'yyyy-MM-dd')"
    

    另一种选择可能是仅使用您收到的字符串的前 10 个字符作为日期:date="item.createdAt.substring(0,9)"

    【讨论】:

      【解决方案2】:

      您是否尝试过类似::date="item.createdAt.substr(0, 10)"

      【讨论】:

        【解决方案3】:

        根据我的经验,在 JS 中格式化日期时间的最简单方法是使用 Moment.js 库 (https://momentjs.com/)。您可以在将日期时间字符串传递给您的子组件之前重新格式化它。

        或者,如果您不想依赖第三方库并且您知道日期时间字符串将始终以该格式传递,我想您可以使用item.createdAt.slice(0, 10)

        【讨论】:

        • 我最近还发现,moment 被认为是遗留项目Moment Status,moment.js 建议不要在新项目中使用 moment.js。
        【解决方案4】:

        Moment.js can be very helpful with dates and times

        Moment Docs

        moment("String").format('L'); // 2020 年 4 月 11 日

        【讨论】:

          猜你喜欢
          • 2020-06-02
          • 1970-01-01
          • 1970-01-01
          • 2014-08-04
          • 1970-01-01
          • 2013-12-27
          • 1970-01-01
          • 1970-01-01
          • 2021-10-06
          相关资源
          最近更新 更多