Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vuejs timeago filter (Milliseconds to Readable string)
/*
It converts timestamp / milliseconds to readable time ago string. for eg. 12 mins ago, 1 month ago
How to use?
import { timeago } from '@/filters.js';
export default {
name: ...,
filters:{timeago},
}
in HTML
<div class="time">
{{post.date | timeago(ctime)}}
</div>
Then in main.js
data: () => ({
timer:null, ctime: Date.now()
}),
created(){
this.timer = setInterval(() => {this.ctime = Date.now()}, 10000);
},
beforeDestroy(){
clearInterval(this.timer)
}
*/
export const timeago = (ptime, ctime) =>{
if (!ptime || !ctime) return ''
let ntime = new Date(ptime * 1000),
seconds = Math.floor((ctime - ntime) / 1000),
intervals = [Math.floor(seconds / 31536000), Math.floor(seconds / 2592000), Math.floor(seconds / 604800),
Math.floor(seconds / 86400), Math.floor(seconds / 3600),Math.floor(seconds / 60)
],
times = ['year', 'month', 'week', 'day', 'hr', 'min'],
key, res;
for (key in intervals) {
if (intervals[key] > 1){
res = intervals[key] + ' ' + times[key] + 's ';
return res;
}else if (intervals[key] === 1){
res = intervals[key] + ' ' + times[key] + ' ';
return res;
}
}
return 'few secs';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.