Php - 从几天到几周/天

时间:2012-01-02 15:45:27

标签: php algorithm

我将来会有很多日子约会,但想知道它有多少个星期和几天。另外,注意到如果它不到一周,那么它只返回相同的数字。

这可能吗?

e.g。 17天将是2周和3天

e.g。 4天将是4天

7 个答案:

答案 0 :(得分:7)

我会尝试这样的事情:

$days = 17;
$weeks = floor($days / 7);
$dayRemainder = $days % 7;
echo $days.'<br/>'.$weeks.'<br/>'.$dayRemainder;//add whatever logic you need here to get the display the way you want it.

答案 1 :(得分:1)

$weeks = intval($days / 7);
$days = $days % 7;

if($weeks)
{
    printf("%d weeks", $weeks);
}
if($days)
{
    if($weeks)
    {
        printf(" and ");
    }
    printf("%d days", $days);
}

答案 2 :(得分:1)

这一切都应该有效

function getnumweeks(d) {
   totalDays = d;
   numWeeks = floor(d/7);
   if numWeeks != 0 {
      extraDays = totalDays % 7;
      return array(extraDays, numWeeks);
   } else {
      return array(totalDays, 0)
   }
}

然后你可以这样打电话和使用它:

ans = getnumweeks(17)

ans[0] <- Contains number of days
ans[1] <- Contains Number of Weeks

答案 3 :(得分:0)

正如Piskvor所提到的,你应该使用模运算符:

$weeks = $days/7;
$daysleft = $days%7;

答案 4 :(得分:0)

假设x是天数,W是周的输出值,D是剩余天数的输出值。

首先进行整数除法

W = x / 7;

然后你拿余数: D = x%7;

答案 5 :(得分:0)

$num_days = $databack30[days_to_next_event]; 
$weeks = floor($num_days/7); 
$days = $num_days % 7;

if($weeks>'0'){ $whenitis = ' in '.$weeks.' weeks and '.$days.' days'; }

else { $whenitis = ' in '.$days.' days'; }

答案 6 :(得分:-1)

我建议你重新使用这个强大的功能日期:

http://www.addedbytes.com/lab/php-datediff-function/

php weeks between 2 dates

中所述

或从该代码中获取灵感。