のような日時スタンプからの経過時間を見つける方法2010-04-28 17:25:43
、最終的な出力テキストはxx Minutes Ago
/のようにする必要がありますxx Days Ago
17 に答える
答えのほとんどは、日付を文字列から時刻に変換することに焦点を当てているようです。日付を「5日前」の形式にすることなどを考えているようですね。
これが私がそれを行う方法です:
$time = strtotime('2010-04-28 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
私はそれをテストしていませんが、動作するはずです。
結果は次のようになります
event happened 4 days ago
また
event happened 1 minute ago
乾杯
人間が読める時間形式のように、文法的に正しい Facebook になる PHP 関数を共有したい。
例:
echo get_time_ago(strtotime('now'));
結果:
1分以内
function get_time_ago($time_stamp)
{
$time_difference = strtotime('now') - $time_stamp;
if ($time_difference >= 60 * 60 * 24 * 365.242199)
{
/*
* 60 seconds/minute * 60 minutes/hour * 24 hours/day * 365.242199 days/year
* This means that the time difference is 1 year or more
*/
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 365.242199, 'year');
}
elseif ($time_difference >= 60 * 60 * 24 * 30.4368499)
{
/*
* 60 seconds/minute * 60 minutes/hour * 24 hours/day * 30.4368499 days/month
* This means that the time difference is 1 month or more
*/
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 30.4368499, 'month');
}
elseif ($time_difference >= 60 * 60 * 24 * 7)
{
/*
* 60 seconds/minute * 60 minutes/hour * 24 hours/day * 7 days/week
* This means that the time difference is 1 week or more
*/
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 7, 'week');
}
elseif ($time_difference >= 60 * 60 * 24)
{
/*
* 60 seconds/minute * 60 minutes/hour * 24 hours/day
* This means that the time difference is 1 day or more
*/
return get_time_ago_string($time_stamp, 60 * 60 * 24, 'day');
}
elseif ($time_difference >= 60 * 60)
{
/*
* 60 seconds/minute * 60 minutes/hour
* This means that the time difference is 1 hour or more
*/
return get_time_ago_string($time_stamp, 60 * 60, 'hour');
}
else
{
/*
* 60 seconds/minute
* This means that the time difference is a matter of minutes
*/
return get_time_ago_string($time_stamp, 60, 'minute');
}
}
function get_time_ago_string($time_stamp, $divisor, $time_unit)
{
$time_difference = strtotime("now") - $time_stamp;
$time_units = floor($time_difference / $divisor);
settype($time_units, 'string');
if ($time_units === '0')
{
return 'less than 1 ' . $time_unit . ' ago';
}
elseif ($time_units === '1')
{
return '1 ' . $time_unit . ' ago';
}
else
{
/*
* More than "1" $time_unit. This is the "plural" message.
*/
// TODO: This pluralizes the time unit, which is done by adding "s" at the end; this will not work for i18n!
return $time_units . ' ' . $time_unit . 's ago';
}
}
私はあなたが望むことをするべき機能を持っていると思います:
function time2string($timeline) {
$periods = array('day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1);
foreach($periods AS $name => $seconds){
$num = floor($timeline / $seconds);
$timeline -= ($num * $seconds);
$ret .= $num.' '.$name.(($num > 1) ? 's' : '').' ';
}
return trim($ret);
}
と の違いに適用するだけtime()
ですstrtotime('2010-04-28 17:25:43')
。
print time2string(time()-strtotime('2010-04-28 17:25:43')).' ago';
@arnorhsの回答を改善するために、より正確な結果を得る機能を追加しました。たとえば、ユーザーが参加してからの年、月、日、時間などが必要な場合。
返す精度のポイント数を指定できる新しいパラメーターを追加しました。
function get_friendly_time_ago($distant_timestamp, $max_units = 3) {
$i = 0;
$time = time() - $distant_timestamp; // to get the time since that moment
$tokens = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
];
$responses = [];
while ($i < $max_units && $time > 0) {
foreach ($tokens as $unit => $text) {
if ($time < $unit) {
continue;
}
$i++;
$numberOfUnits = floor($time / $unit);
$responses[] = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
$time -= ($unit * $numberOfUnits);
break;
}
}
if (!empty($responses)) {
return implode(', ', $responses) . ' ago';
}
return 'Just now';
}
php Datetime クラスを使用する場合は、次を使用できます。
function time_ago(Datetime $date) {
$time_ago = '';
$diff = $date->diff(new Datetime('now'));
if (($t = $diff->format("%m")) > 0)
$time_ago = $t . ' months';
else if (($t = $diff->format("%d")) > 0)
$time_ago = $t . ' days';
else if (($t = $diff->format("%H")) > 0)
$time_ago = $t . ' hours';
else
$time_ago = 'minutes';
return $time_ago . ' ago (' . $date->format('M j, Y') . ')';
}
数学的に計算された例の大部分は、日付の厳しい制限があり2038-01-18
、架空の日付では機能しないことに注意してください。
DateTime
ベースとなる例が不足してDateInterval
いたので、OP のニーズを満たす多目的関数を提供したいと考えました1 month 2 days ago
。経過時間の代わりに日付を表示する制限や、経過時間の結果の一部を除外する制限など、他の多くのユースケースと共に。
さらに、ほとんどの例では、現在の時刻からの経過が想定されています。以下の関数を使用すると、目的の終了日でオーバーライドできます。
/**
* multi-purpose function to calculate the time elapsed between $start and optional $end
* @param string|null $start the date string to start calculation
* @param string|null $end the date string to end calculation
* @param string $suffix the suffix string to include in the calculated string
* @param string $format the format of the resulting date if limit is reached or no periods were found
* @param string $separator the separator between periods to use when filter is not true
* @param null|string $limit date string to stop calculations on and display the date if reached - ex: 1 month
* @param bool|array $filter false to display all periods, true to display first period matching the minimum, or array of periods to display ['year', 'month']
* @param int $minimum the minimum value needed to include a period
* @return string
*/
function elapsedTimeString($start, $end = null, $limit = null, $filter = true, $suffix = 'ago', $format = 'Y-m-d', $separator = ' ', $minimum = 1)
{
$dates = (object) array(
'start' => new DateTime($start ? : 'now'),
'end' => new DateTime($end ? : 'now'),
'intervals' => array('y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second'),
'periods' => array()
);
$elapsed = (object) array(
'interval' => $dates->start->diff($dates->end),
'unknown' => 'unknown'
);
if ($elapsed->interval->invert === 1) {
return trim('0 seconds ' . $suffix);
}
if (false === empty($limit)) {
$dates->limit = new DateTime($limit);
if (date_create()->add($elapsed->interval) > $dates->limit) {
return $dates->start->format($format) ? : $elapsed->unknown;
}
}
if (true === is_array($filter)) {
$dates->intervals = array_intersect($dates->intervals, $filter);
$filter = false;
}
foreach ($dates->intervals as $period => $name) {
$value = $elapsed->interval->$period;
if ($value >= $minimum) {
$dates->periods[] = vsprintf('%1$s %2$s%3$s', array($value, $name, ($value !== 1 ? 's' : '')));
if (true === $filter) {
break;
}
}
}
if (false === empty($dates->periods)) {
return trim(vsprintf('%1$s %2$s', array(implode($separator, $dates->periods), $suffix)));
}
return $dates->start->format($format) ? : $elapsed->unknown;
}
1 つの注意点 - 指定されたフィルター値に対して取得された間隔は、次の期間に持ち越されません。フィルタは、指定された期間の結果の値を表示するだけで、必要なフィルタの合計のみを表示するために期間を再計算しません。
使用法
OPが最高の期間を表示する必要があるため(2015-02-24現在)。
echo elapsedTimeString('2010-04-26');
/** 4 years ago */
複合期間を表示し、カスタムの終了日を提供するには (時間の不足と架空の日付に注意してください)。
echo elapsedTimeString('1920-01-01', '2500-02-24', null, false);
/** 580 years 1 month 23 days ago */
フィルタリングされた期間の結果を表示するには(配列の順序は関係ありません)。
echo elapsedTimeString('2010-05-26', '2012-02-24', null, ['month', 'year']);
/** 1 year 8 months ago */
制限に達した場合に、提供された形式 (デフォルト Ymd) で開始日を表示します。
echo elapsedTimeString('2010-05-26', '2012-02-24', '1 year');
/** 2010-05-26 */
他にもたくさんのユースケースがあります。また、開始、終了、または制限引数に UNIX タイムスタンプおよび/または DateInterval オブジェクトを受け入れるように簡単に適合させることもできます。
私は Mithun のコードが気に入りましたが、より合理的な回答が得られるように少し調整しました。
function getTimeSince($eventTime)
{
$totaldelay = time() - strtotime($eventTime);
if($totaldelay <= 0)
{
return '';
}
else
{
$first = '';
$marker = 0;
if($years=floor($totaldelay/31536000))
{
$totaldelay = $totaldelay % 31536000;
$plural = '';
if ($years > 1) $plural='s';
$interval = $years." year".$plural;
$timesince = $timesince.$first.$interval;
if ($marker) return $timesince;
$marker = 1;
$first = ", ";
}
if($months=floor($totaldelay/2628000))
{
$totaldelay = $totaldelay % 2628000;
$plural = '';
if ($months > 1) $plural='s';
$interval = $months." month".$plural;
$timesince = $timesince.$first.$interval;
if ($marker) return $timesince;
$marker = 1;
$first = ", ";
}
if($days=floor($totaldelay/86400))
{
$totaldelay = $totaldelay % 86400;
$plural = '';
if ($days > 1) $plural='s';
$interval = $days." day".$plural;
$timesince = $timesince.$first.$interval;
if ($marker) return $timesince;
$marker = 1;
$first = ", ";
}
if ($marker) return $timesince;
if($hours=floor($totaldelay/3600))
{
$totaldelay = $totaldelay % 3600;
$plural = '';
if ($hours > 1) $plural='s';
$interval = $hours." hour".$plural;
$timesince = $timesince.$first.$interval;
if ($marker) return $timesince;
$marker = 1;
$first = ", ";
}
if($minutes=floor($totaldelay/60))
{
$totaldelay = $totaldelay % 60;
$plural = '';
if ($minutes > 1) $plural='s';
$interval = $minutes." minute".$plural;
$timesince = $timesince.$first.$interval;
if ($marker) return $timesince;
$first = ", ";
}
if($seconds=floor($totaldelay/1))
{
$totaldelay = $totaldelay % 1;
$plural = '';
if ($seconds > 1) $plural='s';
$interval = $seconds." second".$plural;
$timesince = $timesince.$first.$interval;
}
return $timesince;
}
}
どのバージョンの PHP でも動作するオプションの 1 つは、既に提案されていることを実行することです。これは次のようなものです。
$eventTime = '2010-04-28 17:25:43';
$age = time() - strtotime($eventTime);
これにより、年齢が秒単位で表示されます。そこから、好きなように表示できます。
ただし、このアプローチの問題点の 1 つは、DST による時間のずれが考慮されないことです。それが問題でない場合は、それを選択してください。それ以外の場合は、DateTime クラスで diff() メソッドを使用することをお勧めします。残念ながら、これは少なくとも PHP 5.3 を使用している場合にのみ使用できるオプションです。
[saved_date]をタイムスタンプに変換します。現在のタイムスタンプを取得します。
現在のタイムスタンプ-[saved_date]タイムスタンプ。
次に、date();でフォーマットできます。
通常、strtotime()関数を使用して、ほとんどの日付形式をタイムスタンプに変換できます。
This oneを使用すると、
$previousDate = '2013-7-26 17:01:10';
$startdate = new DateTime($previousDate);
$endDate = new DateTime('now');
$interval = $endDate->diff($startdate);
echo$interval->format('%y years, %m months, %d days');
これを参照して ください http://ca2.php.net/manual/en/dateinterval.format.php
次のリポジトリのいずれかを試してください。
https://github.com/salavert/time-ago-in-words
https://github.com/jimmiw/php-time-ago
私は後者を使い始めたばかりで、トリックを行いますが、問題の日付が遠すぎる場合の正確な日付でのスタックオーバーフロースタイルのフォールバックはなく、将来の日付のサポートもありません-APIは少しファンキーですが、少なくとも一見完璧に動作し、維持されています...
自分で書いた
function getElapsedTime($eventTime)
{
$totaldelay = time() - strtotime($eventTime);
if($totaldelay <= 0)
{
return '';
}
else
{
if($days=floor($totaldelay/86400))
{
$totaldelay = $totaldelay % 86400;
return $days.' days ago.';
}
if($hours=floor($totaldelay/3600))
{
$totaldelay = $totaldelay % 3600;
return $hours.' hours ago.';
}
if($minutes=floor($totaldelay/60))
{
$totaldelay = $totaldelay % 60;
return $minutes.' minutes ago.';
}
if($seconds=floor($totaldelay/1))
{
$totaldelay = $totaldelay % 1;
return $seconds.' seconds ago.';
}
}
}
経過時間を調べるために、私は通常、フォーマットされたタイムスタンプtime()
の代わりに使用します。date()
次に、後者の値と前の値の差を取得し、それに応じてフォーマットします。 time()
の代わりにはなりませんが、date()
経過時間を計算するときに完全に役立ちます。
例:
の値は、time()
このよう1274467343
に1秒ごとに増加します。したがって$erlierTime
、値1274467343
と$latterTime
値を使用して1274467500
、$latterTime - $erlierTime
経過時間を秒単位で取得することができます。
最近これをしなければならなかった - これが誰かに役立つことを願っています。すべての可能性に対応しているわけではありませんが、プロジェクトに対する私のニーズは満たしていました。
https://github.com/duncanheron/twitter_date_format
https://github.com/duncanheron/twitter_date_format/blob/master/twitter_date_format.php
ここでは、日時からの経過時間を見つけるためにカスタム関数を使用しています。
echo Datetodays('2013-7-26 17:01:10'); 関数 Datetodays($d) { $date_start = $d; $date_end = date('Ymd H:i:s'); define('SECOND', 1); define('MINUTE', SECOND * 60); define('HOUR', MINUTE * 60); define('DAY', HOUR * 24); define('週', 日 * 7); $t1 = strtotime($date_start); $t2 = strtotime($date_end); もし ($t1 > $t2) { $diffrence = $t1 - $t2; } そうしないと { $diffrence = $t2 - $t1; } //echo "
".$date_end." ".$date_start." ".$diffrence; $results['major'] = array(); // 日時関係で大きい方の数値を表す整数 $results1 = 配列(); $string = ''; $results['major']['weeks'] = floor($diffrence / WEEK); $results['major']['days'] = floor($diffrence / DAY); $results['major']['hours'] = floor($diffrence / HOUR); $results['major']['minutes'] = floor($diffrence / MINUTE); $results['major']['seconds'] = floor($diffrence / SECOND); //print_r($results); // ロジック: // ステップ 1: 主な結果を取り、生の秒数に変換します (差の秒数は少なくなります) // 例: $result = ($results['major']['weeks']*WEEK) // ステップ 2: 差 (合計時間) から小さい方の数 (結果) を引く // 例: $minor_result = $difference - $result // ステップ 3: 結果の時間を秒単位で取得し、それをマイナー形式に変換します // 例: floor($minor_result/DAY) $results1['weeks'] = floor($diffrence / WEEK); $results1['days'] = floor((($diffrence - ($results['major']['weeks'] * WEEK)) / DAY)); $results1['hours'] = floor((($diffrence - ($results['major']['days'] * DAY)) / HOUR)); $results1['minutes'] = floor((($diffrence - ($results['major']['hours'] * HOUR)) / MINUTE)); $results1['seconds'] = floor((($diffrence - ($results['major']['minutes'] * MINUTE)) / SECOND)); //print_r($results1); if ($results1['weeks'] != 0 && $results1['days'] == 0) { if ($results1['weeks'] == 1) { $string = $results1['weeks'] . ' 一週間前'; } そうしないと { if ($results1['weeks'] == 2) { $string = $results1['weeks'] . ' 何週間前'; } そうしないと { $string = '2 週間前'; } } } elseif ($results1['weeks'] != 0 && $results1['days'] != 0) { if ($results1['weeks'] == 1) { $string = $results1['weeks'] . ' 一週間前'; } そうしないと { if ($results1['weeks'] == 2) { $string = $results1['weeks'] . ' 何週間前'; } そうしないと { $string = '2 週間前'; } } } elseif ($results1['weeks'] == 0 && $results1['days'] != 0) { if ($results1['days'] == 1) { $string = $results1['days'] . '前日'; } そうしないと { $string = $results1['days'] . ' 数日前'; } } elseif ($results1['days'] != 0 && $results1['hours'] != 0) { $string = $results1['days'] . 「日と」。$results1['hours'] . ' 時間前'; } elseif ($results1['days'] == 0 && $results1['hours'] != 0) { if ($results1['hours'] == 1) { $string = $results1['hours'] . ' 一時間前'; } そうしないと { $string = $results1['hours'] . ' 時間前'; } } elseif ($results1['時間'] != 0 && $results1['分'] != 0) { $string = $results1['hours'] . 「時」と「. $results1['minutes'] . ' 数分前'; } elseif ($results1['時間'] == 0 && $results1['分'] != 0) { if ($results1['minutes'] == 1) { $string = $results1['分'] . '分前'; } そうしないと { $string = $results1['分'] . ' 数分前'; } } elseif ($results1['minutes'] != 0 && $results1['seconds'] != 0) { $string = $results1['分'] . 「分と」。$results1['seconds'] . ' 秒前'; } elseif ($results1['minutes'] == 0 && $results1['seconds'] != 0) { if ($results1['seconds'] == 1) { $string = $results1['seconds'] . '秒前'; } そうしないと { $string = $results1['seconds'] . ' 秒前'; } } $文字列を返します。 } ?>
この関数は、WordPress コア ファイルから直接取得できます。こちらをご覧ください。
http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/formatting.php#L2121
function human_time_diff( $from, $to = '' ) {
if ( empty( $to ) )
$to = time();
$diff = (int) abs( $to - $from );
if ( $diff < HOUR_IN_SECONDS ) {
$mins = round( $diff / MINUTE_IN_SECONDS );
if ( $mins <= 1 )
$mins = 1;
/* translators: min=minute */
$since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
$hours = round( $diff / HOUR_IN_SECONDS );
if ( $hours <= 1 )
$hours = 1;
$since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
$days = round( $diff / DAY_IN_SECONDS );
if ( $days <= 1 )
$days = 1;
$since = sprintf( _n( '%s day', '%s days', $days ), $days );
} elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
$weeks = round( $diff / WEEK_IN_SECONDS );
if ( $weeks <= 1 )
$weeks = 1;
$since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
} elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
$months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
if ( $months <= 1 )
$months = 1;
$since = sprintf( _n( '%s month', '%s months', $months ), $months );
} elseif ( $diff >= YEAR_IN_SECONDS ) {
$years = round( $diff / YEAR_IN_SECONDS );
if ( $years <= 1 )
$years = 1;
$since = sprintf( _n( '%s year', '%s years', $years ), $years );
}
return $since;
}