以下代码是否存在任何问题(第10行和第11行专门针对三元运算符)?它似乎没有用,我无法弄清楚做错了什么。
$week_start = 1388991600; // Jan 5 2014
$week_end = 1401602400; // May 31 2014
// Show the first date's year if it is not in the same year as the end date
$same_years_week = ( $week_start % 31536000 === $week_end % 31536000 ? true : false );
// Show the second date's month if it is not in the same month as the end date
$same_months_week = ( $week_start % 2592000 === $week_end % 2592000 ? true : false );
$week_start_range = date('F j' . ( !$same_years_week ? ', Y' : '' ), $week_start);
$week_end_range = date(( !$same_months_week ? 'F ' : '' ) . ' j, Y', $week_end);
$week_range_label = $week_start_range .' — ' . $week_end_range;
print $week_range_label;
似乎如果在我的代码中的第10行和第11行,我会!$same_years_week
或!$same_months_week
,那么两者总是评估为真(无论日期/年份设置为什么),如果我除掉 !无论给出日期和他们的年/月是什么,他们总是在同一条线上评价为假。
我在沙箱中设置了它:http://sandbox.onlinephpfunctions.com/code/2c61baf7e9d2377dabbdd653921dfba7826580a0
我使用http://www.onlineconversion.com/unix_time.htm生成我的初始变量(模拟我从我网站上的数据库接收它们的格式)。
答案 0 :(得分:2)
尝试:
$same_years_week = ( ( $week_start % 31536000 ) === ( $week_end % 31536000 ) ? true : false );
$same_months_week = ( ( $week_start % 2592000 ) === ( $week_end % 2592000 ) ? true : false );
但是你可以跳过这个三元组,然后做:
$same_years_week = ( $week_start % 31536000 ) === ( $week_end % 31536000 );
$same_months_week = ( $week_start % 2592000 ) === ( $week_end % 2592000 );
答案 1 :(得分:2)
这不是你比较岁月的方式......
$week_start = 1388991600 % 3153600; // 1407600
$week_end = 1401602400 % 3153600; // 14018400
这两个值不同,因此您的IF()失败。
你想:
if (date('Y', $week_start) == date('Y', $week_end))
相反,所以你要比较 ACTUALL 年份值,例如2014 == 2014年。
答案 2 :(得分:0)
hsz说的是什么,? true : false
没有多大意义,可以省略:
$same_years_week = ( ( $week_start % 31536000 ) === ( $week_end % 31536000 ) );
$same_months_week = ( ( $week_start % 2592000 ) === ( $week_end % 2592000 ) );
另外,请注意unix次。如果您不在UTC时区,特别是,如果您在UTC以东,则从“第X天,00:00:00”计算的值可能会包含在前一天,甚至可能会在周末的不同周。