Last active
August 7, 2017 23:43
-
-
Save hail2u/8d96d6ed7fc5995f6e7c292dfef1fe6c to your computer and use it in GitHub Desktop.
datetime属性を持つtime要素を全部相対時刻にするやつ
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
/*! | |
* reldate.js | |
* | |
* LICENSE: http://hail2u.mit-license.org/2016 | |
*/ | |
"use strict"; | |
(function () { | |
const now = Date.now(); | |
const toRelativeDate = function (then) { | |
let diff = 0; | |
if (!Number.isInteger(then)) { | |
return; | |
} | |
diff = parseInt((now - then) / 1000, 10); | |
if (diff < 0) { | |
return; | |
} | |
if (diff < 60) { | |
return diff + "秒前"; | |
} | |
diff = parseInt(diff / 60, 10); | |
if (diff < 60) { | |
return diff + "分前"; | |
} | |
diff = parseInt(diff / 60, 10); | |
if (diff < 24) { | |
return diff + "時間前"; | |
} | |
diff = parseInt(diff / 24, 10); | |
if (diff < 30) { | |
return diff + "日前"; | |
} | |
diff = parseInt(diff / 30, 10); | |
if (diff < 12) { | |
return diff + "ヶ月前"; | |
} | |
return parseInt(diff / 12, 10) + "年前"; | |
}; | |
for (let time of document.querySelectorAll("time")) { | |
let abs = time.getAttribute("datetime"); | |
let rel = ""; | |
if (!abs) { | |
continue; | |
} | |
rel = toRelativeDate(Date.parse(abs)); | |
// 後でまとめてやりたい | |
if (rel) { | |
time.setAttribute("title", abs); | |
time.textContent = rel; | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment