繁体   English   中英

PHP中的日期差异人类格式输出

[英]Date Diff Human Format Output in PHP

好的,我在这个主题上找到了很多话题,但是找不到适合我的话题。

我有一个可以正常工作的脚本,但前提是输入日期是今天,但是我有一个日期,例如Sunday 7th of July at 10:51am ,它的日期是Thursday at 12:33 pm ,等等。 January 1 at 12:33 pm超过一个星期。

到目前为止,这是我的脚本(输入日期$timestamp的格式为Ymd H:i:s

function dateDiff($timestamp) {
if(empty($timestamp)) {
    return "No date provided";
}
// Get time difference and setup arrays
$unix_date = strtotime($timestamp);
if(empty($unix_date)) {    
    return "Bad date";
}
$difference = time() - $unix_date;
$periods = array("second", "minute", "hour", "day", "week", "month", "years");
$lengths = array("60","60","24","7","4.35","12"); 
// Past or present
if ($difference >= 0) {
    $ending = "ago";
} else {
    $difference = -$difference;
    $ending = "to go";
} 
// Figure out difference by looping while less than array length
// and difference is larger than lengths.
$arr_len = count($lengths);
for($j = 0; $j < $arr_len && $difference >= $lengths[$j]; $j++) {
    $difference /= $lengths[$j];
} 
// Round up     
$difference = round($difference); 
// Make plural if needed
if($difference != 1) {
    $periods[$j].= "s";
} 
// Default format
$text = $difference." ".$periods[$j]." ".$ending; 
// over 24 hours
if($j > 2) {
    // future date over a day formate with year
    if($ending == "to go") {
        if($j == 3 && $difference == 1) {
            $text = "Tomorrow at ". date("g:i a", $timestamp);
        } else {
            $text = date("F j, Y \a\\t g:i a", $timestamp);
        }
        return $text;
    } 
    if($j == 3 && $difference == 1) { // Yesterday
        $text = "Yesterday at ". date("g:i a", $timestamp);
    } else if($j == 3) { // Less than a week display -- Monday at 5:28pm
        $text = date("l \a\\t g:i a", $timestamp);
    } else if($j < 6 && !($j == 5 && $difference == 12)) { // Less than a year display -- June 25 at 5:23am
        $text = date("F j \a\\t g:i a", $timestamp);
    } else { // if over a year or the same month one year ago -- June 30, 2010 at 5:34pm
        $text = date("F j, Y \a\\t g:i a", $timestamp);
    }
} 
return $text;
}

谁能看到导致它显示错误信息的东西吗?

固定。 我添加了以下内容。 我的错误报告需要一点时间才能通过,所以一开始我没有看到它们

if(empty($timestamp)) {
    return "No date provided";
} else {
    $timestamp = strtotime($timestamp);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM