Skip to content

Instantly share code, notes, and snippets.

@112KA
Created April 10, 2019 23:16
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 112KA/7fe6129dccafc8ae2236c3e1d54299f6 to your computer and use it in GitHub Desktop.
Save 112KA/7fe6129dccafc8ae2236c3e1d54299f6 to your computer and use it in GitHub Desktop.
指定した日時からの差を時間で返す
{
distanceFrom(utcDateString) {
const date = new Date(utcDateString),
current = new Date(),
seconds = (current.getTime() - date.getTime()) / 1000
// 59分以内だったら、minで返す
if(seconds < 60 * 59) {
return Math.ceil(seconds/60) + '分前'
}
// 23時間以内だったら、hで返す
else if(seconds < 60 * 60 * 23) {
return Math.ceil(seconds/60/60) + '時間前'
}
// 30日以内だったら、dで返す
else if(seconds < 60 * 60 * 24 * 30) {
return Math.ceil(seconds/60/60/24) + '日前'
}
// 335日以内だったら、mで返す
else if(seconds < 60 * 60 * 24 * 335) {
return Math.ceil(seconds/60/60/24/30) + '月前'
}
//それ以上はyで返す
else {
return Math.max(1, Math.floor(seconds/60/60/24/365)) + '年前'
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment