Skip to content

Instantly share code, notes, and snippets.

@dagalti
Last active March 31, 2019 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dagalti/1f836fd76b53c6872d50f4c95aa3bf84 to your computer and use it in GitHub Desktop.
Save dagalti/1f836fd76b53c6872d50f4c95aa3bf84 to your computer and use it in GitHub Desktop.
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