【问题标题】:Formatting database date to AM/PM time (vue)将数据库日期格式化为 AM/PM 时间(vue)
【发布时间】:2019-01-18 03:24:32
【问题描述】:

我从我的数据库中以2018-08-08 15:38:48 格式接收日期,但我希望它改为显示3:38 pm

我只是不确定何时进行此更改,我可以在发布时进行更改吗?它们是发送给某人的消息的日期。

当前代码:

<div v-for="messages in userMessages">
   <div class="date">
       {{ user.created_at }}
   </div>
</div>

输出:

2018-08-08 15:38:48

如何在 vue 中转换日期? (当它在 v-for 中时?)

【问题讨论】:

  • This question 让您了解如何在 vue 中使用 JavaScript 格式化日期字符串。这不是您的用例,但您可以从这里开始。

标签: php laravel vue.js vuejs2


【解决方案1】:

Vue 不提供日期格式。您将需要自己的过滤器来格式化日期。或者你使用如下的包:https://github.com/brockpetrie/vue-moment#readme

<span>{{ someDate | moment("hh:mm a") }}</span>

【讨论】:

    【解决方案2】:

    Vue.js 本身不允许日期以不同的方式格式化。

    我建议您使用更著名的库,例如 moment.js 来格式化您想要的日期。

    例如:

    import moment from 'moment'
    
    Vue.filter('formatDate', function(value) {
      if (value) {
        return moment(String(value)).format('MM/DD/YYYY hh:mm')
      }
    }
    

    【讨论】:

      【解决方案3】:

      https://momentjs.com/

      你如何使用它?

      你可以这样使用。

      moment('2018-08-08 15:38:48').format('LTS'); // 03:38:48 PM
      

      【讨论】:

        【解决方案4】:

        您的日期时间格式不是我们想要的 ISO 标准,但我们会接受它...在处理日期时,最好在收到日期后立即将其转换为日期对象。如果它们以 JSON 形式到达,您可以使用 reviver 函数作为 JSON.parse() 的第二个参数来执行此操作。这是一个 reviver 函数,它将为您完成这项工作......

        然后,在你需要显示的地方,你可以用 toLocaleTimeString() 格式化你的时间

        function nReviver(key, value) {
                var a;
                if (typeof value === "string") {
                    a = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d*)?$/.exec(value);
                    if (a) {
                        return new Date(a[0]);
                    }
                }
                return value;
            }
            
            // do this when you receive your data from the server and all
            // dates, wherever they are in the JSON, will be converted to date objects
            var myObj = JSON.parse('{"myDate":"2018-08-08 15:38:48"}',nReviver)
        
            // ...then, when you want to display, format with toLocaleTimeString()
            console.log(
              myObj.myDate.toLocaleTimeString({},{
                hour12:true,
                hour:'numeric',
                minute:'numeric'
              })
              .toLowerCase()
            )

        【讨论】:

          猜你喜欢
          • 2021-02-17
          • 2021-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-18
          • 1970-01-01
          相关资源
          最近更新 更多