把我的时间变成时间戳php

时间:2012-02-02 16:52:44

标签: php mysql

我有一个当前时间格式化方法:

$time = date('mdY');

我需要将其转回正常的Linux时间戳。我需要动态地做这件事。基本上一个函数是将$时间传递给它,然后它需要将它转换为一个正常的时间戳(我假设是time();)?

谢谢

修改: 当我尝试每个人明显的建议时,我得到一个 警告:在第75行的/home/content/50/5975650/html/checkEntry.php中除以零

function RelativeTime($timeToSend){
    $difference = time() - $timestamp;
    $periods = array("sec", "min", "hour", "day", "week", "month", "years", "decade");
    $lengths = array("60","60","24","7","4.35","12","10");

    if ($difference > 0) { // this was in the past
        $ending = "ago";
    } else { // this was in the future
        $difference = -$difference;
        $ending = "to go";
    }
    for($j = 0; $difference >= $lengths[$j]; $j++)
        $difference /= $lengths[$j];
    $difference = round($difference);
    if($difference != 1) $periods[$j].= "s";
    $text = "$difference $periods[$j] $ending";
    return $text;
}

//检查服务呼叫状态&如果发现未付邮件

$query = "SELECT id, account, status, dateEntered FROM service WHERE status = 'Unpaid'";
        $result = mysql_query($query) or die(mysql_error());

    while($row = mysql_fetch_row($result)){

                $account = $row[1];
                $status = $row[2];
                $dateEntered = $row[3];

                $timestamp = strtotime($dateEntered);   
                            $timeToSend = RelativeTime($timestmap);

              // mailStatusUpdate($account, $status, $timeToSend);

        }   

2 个答案:

答案 0 :(得分:0)

像这样使用strptime

$tm = strptime($time, '%m%d%Y');
$timestamp = strtotime(sprintf("%04d-%02d-%02d", $tm['tm_year'], $tm['tm_mon']+1, $tm['tm_mday']));

如果您使用PHP 5.3或更高版本,您还可以使用date_parse_from_format

至于你问题的其他部分,如果时差大于10年,你的代码会有错误。

任何分裂前差异的初始值是多少?我的猜测是它超过10年,所以你用完“长度”,即系统试图达到未定义的$ length [8],计为零,所以它试图除以零。< / p>

答案 1 :(得分:0)

开始,函数$difference = time() - $timestamp;的第一行引用未设置的$ timestamp,因为$timeToSend是传递给函数的内容。这导致$ difference始终等于time()

第二,除以零错误是从for循环for($j = 0; $difference >= $lengths[$j]; $j++)到达$lengths[j]不存在的点(因为第一个错误,$ difference == 0),所以循环继续,直到$j超出$lengths的范围。我建议在for循环中检查$lengths[$j],如for($j = 0; array_key_exists($j,$lengths)&&$difference >= $lengths[$j]; $j++)

最后:

function RelativeTime($timeToSend){
$difference = time() - $timestamp;
$periods = array("sec", "min", "hour", "day", "week",
"month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");

if ($difference > 0) { // this was in the past
$ending = "ago";
} else { // this was in the future
$difference = -$difference;
$ending = "to go";
}
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] $ending";
return $text;
}
echo RelativeTime(strtotime('-3 months'))."\n";
echo RelativeTime(strtotime(0));

And example working.