Skip to content

Instantly share code, notes, and snippets.

@kitak
Created September 16, 2016 05:52
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 kitak/0e7c1a52d79c18b9e1d954d369c7393a to your computer and use it in GitHub Desktop.
Save kitak/0e7c1a52d79c18b9e1d954d369c7393a to your computer and use it in GitHub Desktop.
日時表記
import moment from 'moment';
function fromNow (unixTime) {
if (!unixTime) {
return '';
}
let target = moment.unix(unixTime);
const diffMinutes = moment().diff(target, 'minutes');
const diffHours = moment().diff(target, 'hours');
const diffDays = moment().diff(target, 'days');
const diffWeeks = moment().diff(target, 'weeks');
const diffMonths = moment().diff(target, 'months');
const diffYears = moment().diff(target, 'years');
let text = '';
console.assert(diffMinutes >= 0);
if (diffMinutes === 0) {
text = 'たった今';
} else if (diffMinutes >= 1 && diffMinutes <= 59) {
text = `${diffMinutes}分前`;
} else if (diffHours >= 1 && diffHours <= 23) {
text = `${diffHours}時間前`;
} else if (diffDays >= 1 && diffDays <= 5) {
text = `${diffDays}日前`;
} else if (diffWeeks >= 1 && diffWeeks <= 4) {
text = `${diffWeeks}週間前`;
} else if (diffMonths >= 1 && diffMonths <= 11) {
text = `${diffMonths}ヶ月前`;
} else if (diffYears >= 1 && diffYears <= 11) {
text = `${diffYears}年前`;
}
return text;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment