Gerardo Grignoli Gerardo Grignoli - 3 months ago 61
Javascript Question

How to format a (possibly null/empty) date in VueJS

Using Vue.JS 1.0, I couldn't find a simple way to properly format a JSON date that can be empty.

I tried with vue-filter npm package

date filter
but it fails if the date is empty. For example if my data is:

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


returns

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


The code i am using:

<!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>


What is the proper way to format a date, that will also make show blank if date is null?

Answer

Write a custom filter to wrap the date filter. If the input is null, return null, otherwise return Vue.filter('date')(input)

Vue.filter('dateOrNull', function(d) {
  return d ? Vue.filter('date')(d) : 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}}</div>
  </div>
</div>

Comments