JavaScipt
1var ux = '1556717071031';
2var date = new Date(parseInt(ux, 10));
3var month = date.getMonth() + 1;
4var day = date.getDate();
5var dateString = date.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
6console.log(dateString);
・~秒前、~分前の値は切り捨てです。
・1か月を一律(365.25 / 12)日とみなして計算しています。
・未来の値は考慮していません。
JavaScipt
1function toRelativeDate(ux) {
2 var date = new Date(parseInt(ux, 10));
3 var seconds = (new Date - date) / 1000;
4 var days = seconds / 3600 / 24;
5
6 if (seconds < 1) return '今';
7 if (seconds < 60) return Math.floor(seconds) + '秒前';
8 if (seconds < 3600) return Math.floor(seconds / 60) + '分前';
9 if (seconds < 3600 * 24) return Math.floor(seconds / 3600) + '時間前';
10 if (days < 365.25 / 12) return Math.floor(days) + '日前';
11 // 1か月を一律(365.25 / 12)日とみなして計算
12 if (days < 365.25) return Math.floor(days / 365.25 * 12) + 'か月前';
13 return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
14}
15
16// テスト
17
18console.log(toRelativeDate((new Date().valueOf() - 500).toString()));
19console.log(toRelativeDate((new Date().valueOf() - 12700).toString()));
20console.log(toRelativeDate((new Date().valueOf() - 34.5 * 60000).toString()));
21console.log(toRelativeDate((new Date().valueOf() - 23.6 * 3600000).toString()));
22console.log(toRelativeDate((new Date().valueOf() - 21.5 * 24 * 3600000).toString()));
23console.log(toRelativeDate((new Date().valueOf() - 360 * 24 * 3600000).toString()));
24console.log(toRelativeDate(new Date(2018, 5-1, 1).valueOf().toString()));