我正在尝试创建一个PHP函数,我使用以下格式输入$date
变量:03/09/2016 - 12:02。
我创建了一个函数来将这个日期/时间变量转换为一个字符串,表示$date
变量是x天和小时之前。
功能:
$date = $r->date;
function nicetime($date)
{
if(empty($date)) {
return "Geen datum gevonden.";
}
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
ini_set('date.timezone', 'Europe/Berlin');
$now = time('Y-m-d H:i:s');
$unix_date = $date;
// check validity of date
if(empty($unix_date)) {
return "Error.";
}
// is it future date or past date
if($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "ago";
} else {
$difference = $unix_date - $now;
$tense = "from now";
}
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1) {
$periods[$j].= "s";
}
return "$difference $periods[$j] {$tense}";
}
$postdate = nicetime($date);
所以我使用$date
来插入日期。 $postdate
的结果是47年前。
有人知道我做错了什么吗?因为我不应该在47年前得到。
答案 0 :(得分:3)
因此,让我们将您的工作分成3个步骤:
第1步:分叉时间和日期。然后使用long
function获取strtotime()
时间
第2步:从long
获取当前time()
时间功能
第3步:现在 - Unix日期
<?php
$date = $r->date;
function nicetime($date)
{
if(empty($date)) {
return "Geen datum gevonden.";
}
$r1 = split('/', $date);
$day = $r1[0];
$month = $r1[1];
$year = split(' ', $r1[2]);
$year = $year[0];
$r1 = split('-', $date);
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
ini_set('date.timezone', 'Europe/Berlin');
$now = time();
$unix_date = strtotime($month.'/'.$day.'/'.$year.' '. $r1[1])."</br>";;
// check validity of date
if(empty($unix_date)) {
return "Error.";
}
// is it future date or past date
if($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "ago";
} else {
$difference = $unix_date - $now;
$tense = "from now";
}
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1) {
$periods[$j].= "s";
}
return "$difference $periods[$j] {$tense}";
}
$postdate = nicetime($date); // 2 days ago
echo $postdate;
?>
顺便说一句,你做得很好。
更新:使用循环到此函数时,请确保将函数包含在条件块中:
if (!function_exists('nicetime')) {
// ... proceed to declare your function
}