vue怎麼自訂個過濾器將時間戳轉換為小於24小時顯示今天大於24小時顯示昨天大於48小時顯示年-月-日
簡單的模仿了白雲蒼狗的文章 但是不是起很大的作用
過濾後的結果 2013-03-22 02:20
<p id="app">
<input type="text" v-model="a"/>
<hr />
<span>
{{daitem |times}}
</span>
</p>
<script type="text/javascript">
Vue.filter('times',function (item) {
var date = (typeof item === 'number') ? new Date(item) : new Date((item || '').replace(/-/g, '/'))
// console.log(date)
var diff = (((new Date()).getTime() - date.getTime()) / 1000)
var dayDiff = Math.floor(diff / 86400)
var isValidDate = Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime())
if (!isValidDate) {
console.error('not a valid date')
return item
}
var today = new Date(date)
var year = today.getFullYear()
var month = ('0' + (today.getMonth() + 1)).slice(-2)
var day = ('0' + today.getDate()).slice(-2)
var hour = ('0' + today.getHours()).slice(-2)
var minute = ('0'+today.getMinutes()).slice(-2)
if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
return `${year}-${month}-${day} ${hour}:${minute}`
}
return dayDiff === 0 && (
diff < 86400 && '今天'
) ||
dayDiff < 2 && '昨天' + `${hour}:${minute}`||
dayDiff < 3 && '前天' + `${hour}:${minute}`||
dayDiff >3 && `${year}-${month}-${day}`
});
var vm = new Vue({
el: '#app',
data: {
daitem: '2013-3-22 2:20'
},
});
</script>
應該用自訂指令更好。