Last active
March 31, 2019 00:09
-
-
Save dagalti/1f836fd76b53c6872d50f4c95aa3bf84 to your computer and use it in GitHub Desktop.
Vuejs timeago filter (Milliseconds to Readable string)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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