gpt4 book ai didi

javascript - 如何在 VueJS 中格式化(可能为空/空)日期

转载 作者:搜寻专家 更新时间:2023-10-30 23:00:37 24 4
gpt4 key购买 nike

使用 Vue.JS 1.0,我找不到一种简单的方法来正确格式化可以为空的 JSON 日期。

我试过 vue-filter npm package date filter 但如果日期为空则失败。例如,如果我的数据是:

{ name: "John", birthday: null },  /* unknown birthday */
{ name: "Maria", birthday: "2012-04-23T18:25:43.511Z" },

返回

John 12/31/1969 9:00:00 PM  <-- null date should be blank 
Maria 4/23/2012 3:25:43 PM <-- ok

我使用的代码:

<!DOCTYPE html><html>
<head>
<script src="lib/vue/dist/vue.min.js"></script>
<script src="lib/vue-filter/dist/vue-filter.min.js"></script>
</head>
<body>
<div id="app">
<h1>Without Filter:</h1>
<div v-for="person in list">
<div>{{person.name}} {{person.birthday}}</div>
</div>
<h1>With Filter:</h1>
<div v-for="person in list">
<div>{{person.name}} {{person.birthday | date }}</div>
</div>
</div>
<script>
new Vue({
el: "#app",
data: {
list: [
{ name: "John", birthday: null },
{ name: "Maria", birthday: "2012-04-23T18:25:43.511Z" },
]
}
});
</script>
</body>
</html>

格式化日期的正确方法是什么,如果日期为空,也会使显示空白?

最佳答案

编写一个自定义过滤器来包装日期过滤器。如果输入为null,则返回null,否则返回Vue.filter('date')(input)

Vue.filter('dateOrNull', function(d, ...others) {
return d ? Vue.filter('date')(d, ...others) : null;
});
new Vue({
el: "#app",
data: {
list: [{
name: "John",
birthday: null
}, {
name: "Maria",
birthday: "2012-04-23T18:25:43.511Z"
}, ]
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<script src="//rawgit.com/wy-ei/vue-filter/master/dist/vue-filter.min.js"></script>
<div id="app">
<h1>Without Filter:</h1>
<div v-for="person in list">
<div>{{person.name}} {{person.birthday}}</div>
</div>
<h1>With Filter:</h1>
<div v-for="person in list">
<div>{{person.name}} {{person.birthday | dateOrNull '%B'}}</div>
</div>
</div>

关于javascript - 如何在 VueJS 中格式化(可能为空/空)日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com