Date
問題は、スタック オーバーフローに表示される時間と同様に、経過時間を示す文字列としてJavaScript をフォーマットする方法です。
例えば
- 1分前
- 1時間前
- 1日前
- 1ヶ月前
- 1年前
Date
問題は、スタック オーバーフローに表示される時間と同様に、経過時間を示す文字列としてJavaScript をフォーマットする方法です。
例えば
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + " years";
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + " months";
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + " days";
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + " hours";
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + " minutes";
}
return Math.floor(seconds) + " seconds";
}
var aDay = 24*60*60*1000;
console.log(timeSince(new Date(Date.now()-aDay)));
console.log(timeSince(new Date(Date.now()-aDay*2)));
この場合はやり過ぎかもしれませんが、機会があればmoment.jsは素晴らしいです!
Moment.js は JavaScript の日時ライブラリです。このようなシナリオで使用するには、次のようにします。
moment(yourdate).fromNow()
http://momentjs.com/docs/#/displaying/fromnow/
2018 年の補遺: Luxonは新しい近代的な図書館であり、一見の価値があるかもしれません!
これにより、「2 日前」「今から 10 分後」などの過去および以前の時刻形式が表示され、Date オブジェクト、数値タイムスタンプ、または日付文字列のいずれかを渡すことができます。
function time_ago(time) {
switch (typeof time) {
case 'number':
break;
case 'string':
time = +new Date(time);
break;
case 'object':
if (time.constructor === Date) time = time.getTime();
break;
default:
time = +new Date();
}
var time_formats = [
[60, 'seconds', 1], // 60
[120, '1 minute ago', '1 minute from now'], // 60*2
[3600, 'minutes', 60], // 60*60, 60
[7200, '1 hour ago', '1 hour from now'], // 60*60*2
[86400, 'hours', 3600], // 60*60*24, 60*60
[172800, 'Yesterday', 'Tomorrow'], // 60*60*24*2
[604800, 'days', 86400], // 60*60*24*7, 60*60*24
[1209600, 'Last week', 'Next week'], // 60*60*24*7*4*2
[2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7
[4838400, 'Last month', 'Next month'], // 60*60*24*7*4*2
[29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4
[58060800, 'Last year', 'Next year'], // 60*60*24*7*4*12*2
[2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12
[5806080000, 'Last century', 'Next century'], // 60*60*24*7*4*12*100*2
[58060800000, 'centuries', 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100
];
var seconds = (+new Date() - time) / 1000,
token = 'ago',
list_choice = 1;
if (seconds == 0) {
return 'Just now'
}
if (seconds < 0) {
seconds = Math.abs(seconds);
token = 'from now';
list_choice = 2;
}
var i = 0,
format;
while (format = time_formats[i++])
if (seconds < format[0]) {
if (typeof format[2] == 'string')
return format[list_choice];
else
return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;
}
return time;
}
var aDay = 24 * 60 * 60 * 1000;
console.log(time_ago(new Date(Date.now() - aDay)));
console.log(time_ago(new Date(Date.now() - aDay * 2)));
確認していませんが (難しいことではありませんが)、Stack Exchange サイトではjquery.timeago
プラグインを使用してこれらの時間文字列を作成していると思います。
プラグインの使い方は非常に簡単で、クリーンで自動的に更新されます。
簡単なサンプルを次に示します (プラグインのホームページから):
まず、jQuery とプラグインをロードします。
<script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.timeago.js" type="text/javascript"></script>
それでは、DOM Ready のタイムスタンプに添付しましょう。
jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago(); });これにより、タイトル
abbr
にクラスがtimeago
あり、ISO 8601 タイムスタンプが含まれるすべての要素が次の<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>
よう<abbr class="timeago" title="July 17, 2008">about a year ago</abbr>
になります: 約 1 年前. 時間が経過すると、タイムスタンプが自動的に更新されます。
ここでは、Sky Sander のソリューションを少し変更して、日付を文字列として入力できるようにし、「73 秒」ではなく「1 分」などのスパンを表示できるようにします。
var timeSince = function(date) {
if (typeof date !== 'object') {
date = new Date(date);
}
var seconds = Math.floor((new Date() - date) / 1000);
var intervalType;
var interval = Math.floor(seconds / 31536000);
if (interval >= 1) {
intervalType = 'year';
} else {
interval = Math.floor(seconds / 2592000);
if (interval >= 1) {
intervalType = 'month';
} else {
interval = Math.floor(seconds / 86400);
if (interval >= 1) {
intervalType = 'day';
} else {
interval = Math.floor(seconds / 3600);
if (interval >= 1) {
intervalType = "hour";
} else {
interval = Math.floor(seconds / 60);
if (interval >= 1) {
intervalType = "minute";
} else {
interval = seconds;
intervalType = "second";
}
}
}
}
}
if (interval > 1 || interval === 0) {
intervalType += 's';
}
return interval + ' ' + intervalType;
};
var aDay = 24 * 60 * 60 * 1000;
console.log(timeSince(new Date(Date.now() - aDay)));
console.log(timeSince(new Date(Date.now() - aDay * 2)));
Lokelyで使用される短いバージョン:
const intervals = [
{ label: 'year', seconds: 31536000 },
{ label: 'month', seconds: 2592000 },
{ label: 'day', seconds: 86400 },
{ label: 'hour', seconds: 3600 },
{ label: 'minute', seconds: 60 },
{ label: 'second', seconds: 1 }
];
function timeSince(date) {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
const interval = intervals.find(i => i.seconds < seconds);
const count = Math.floor(seconds / interval.seconds);
return `${count} ${interval.label}${count !== 1 ? 's' : ''} ago`;
}
humanized_time_span を見たいかもしれません: https://github.com/layam/js_humanized_time_span
フレームワークにとらわれず、完全にカスタマイズ可能です。
スクリプトをダウンロード/含めるだけで、次のことができます。
humanized_time_span("2011-05-11 12:00:00")
=> '3 hours ago'
humanized_time_span("2011-05-11 12:00:00", "2011-05-11 16:00:00)
=> '4 hours ago'
またはこれさえ:
var custom_date_formats = {
past: [
{ ceiling: 60, text: "less than a minute ago" },
{ ceiling: 86400, text: "$hours hours, $minutes minutes and $seconds seconds ago" },
{ ceiling: null, text: "$years years ago" }
],
future: [
{ ceiling: 60, text: "in less than a minute" },
{ ceiling: 86400, text: "in $hours hours, $minutes minutes and $seconds seconds time" },
{ ceiling: null, text: "in $years years" }
]
}
humanized_time_span("2010/09/10 10:00:00", "2010/09/10 10:00:05", custom_date_formats)
=> "less than a minute ago"
詳細については、ドキュメントを参照してください。
@ user1012181 によって提供されたコードの ES6 バージョン:
const epochs = [
['year', 31536000],
['month', 2592000],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1]
];
const getDuration = (timeAgoInSeconds) => {
for (let [name, seconds] of epochs) {
const interval = Math.floor(timeAgoInSeconds / seconds);
if (interval >= 1) {
return {
interval: interval,
epoch: name
};
}
}
};
const timeAgo = (date) => {
const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000);
const {interval, epoch} = getDuration(timeAgoInSeconds);
const suffix = interval === 1 ? '' : 's';
return `${interval} ${epoch}${suffix} ago`;
};
@ibe-vanmeenen の提案で編集。(ありがとう!)
上記の機能を
function timeSince(date) {
var seconds = Math.floor(((new Date().getTime()/1000) - date)),
interval = Math.floor(seconds / 31536000);
if (interval > 1) return interval + "y";
interval = Math.floor(seconds / 2592000);
if (interval > 1) return interval + "m";
interval = Math.floor(seconds / 86400);
if (interval >= 1) return interval + "d";
interval = Math.floor(seconds / 3600);
if (interval >= 1) return interval + "h";
interval = Math.floor(seconds / 60);
if (interval > 1) return interval + "m ";
return Math.floor(seconds) + "s";
}
それ以外の場合は、「75 分」(1 ~ 2 時間) のように表示されます。また、入力日付が Unix タイムスタンプであると想定するようになりました。
非常に読みやすく、ブラウザ間で互換性のあるコード:
@Travisによって与えられたように
var DURATION_IN_SECONDS = {
epochs: ['year', 'month', 'day', 'hour', 'minute'],
year: 31536000,
month: 2592000,
day: 86400,
hour: 3600,
minute: 60
};
function getDuration(seconds) {
var epoch, interval;
for (var i = 0; i < DURATION_IN_SECONDS.epochs.length; i++) {
epoch = DURATION_IN_SECONDS.epochs[i];
interval = Math.floor(seconds / DURATION_IN_SECONDS[epoch]);
if (interval >= 1) {
return {
interval: interval,
epoch: epoch
};
}
}
};
function timeSince(date) {
var seconds = Math.floor((new Date() - new Date(date)) / 1000);
var duration = getDuration(seconds);
var suffix = (duration.interval > 1 || duration.interval === 0) ? 's' : '';
return duration.interval + ' ' + duration.epoch + suffix;
};
alert(timeSince('2015-09-17T18:53:23'));
これから、unix タイムスタンプ パラメータ、
function timeSince(ts){
now = new Date();
ts = new Date(ts*1000);
var delta = now.getTime() - ts.getTime();
delta = delta/1000; //us to s
var ps, pm, ph, pd, min, hou, sec, days;
if(delta<=59){
ps = (delta>1) ? "s": "";
return delta+" second"+ps
}
if(delta>=60 && delta<=3599){
min = Math.floor(delta/60);
sec = delta-(min*60);
pm = (min>1) ? "s": "";
ps = (sec>1) ? "s": "";
return min+" minute"+pm+" "+sec+" second"+ps;
}
if(delta>=3600 && delta<=86399){
hou = Math.floor(delta/3600);
min = Math.floor((delta-(hou*3600))/60);
ph = (hou>1) ? "s": "";
pm = (min>1) ? "s": "";
return hou+" hour"+ph+" "+min+" minute"+pm;
}
if(delta>=86400){
days = Math.floor(delta/86400);
hou = Math.floor((delta-(days*86400))/60/60);
pd = (days>1) ? "s": "";
ph = (hou>1) ? "s": "";
return days+" day"+pd+" "+hou+" hour"+ph;
}
}
私は js と python で 1 つを作成し、2 つのプロジェクトで使用されています。非常に素晴らしくシンプルです。日付をステートメントでフォーマットするために使用されるシンプルなライブラリ (2kb 未満)です。*** time ago
シンプルで小さく、使いやすく、よくテストされています。
npm install timeago.js
import timeago from 'timeago.js'; // or use script tag
アピを使用しますformat
。
サンプル:
var timeagoIns = timeago();
timeagoIns .format('2016-06-12');
また、リアルタイムでレンダリングすることもできます。
var timeagoIns = timeago();
timeagoIns.render(document.querySelectorAll('time'));