尝试计算字符串时两个日期之间的差异
Trying to work out the difference between two dates when strings
我试图减去 php 中的两个日期,但结果总是 return 为零,即使数据确实有价值并且当我回显日期时 return正确,但我将它们作为字符串格式存储在 wordpress 的 ACF 中。
但是数据是一样的即date_joined
加入日期值为 05/31/2016 06:33:27
日期到期值为 06/14/2016 06:33:27
<?php
$dateJoined = the_field('date_joined', $post_id );
$expiredate = the_field('expiry_date', $post_id );
//Convert them to timestamps.
$difference=(int)abs((strtotime($expiredate) - strtotime($dateJoined))/(60*60*24*30)); // 3
?>
我正在使用
检索值
$dateJoined = the_field('date_joined', $post_id );
$expiredate = the_field('expiry_date', $post_id );
这是高级自定义字段用户检索自定义字段值的方法,但如您所见,它只是 return 一个字符串
您将大约 15 天的时间戳差异除以相当于 30 天的时间戳差异,并将结果转换为整数。因此结果为 0.
对于代码中的大多数用途,以秒为单位的差异就足够了:
$difference = abs((strtotime($expiredate) - strtotime($dateJoined));
如果您需要将该值与更粗略的时间单位中的其他值进行比较,请将比较值(通过相乘)转换为秒。
仅将您的工作值转换为更粗略的单位,以便将结果呈现给用户(例如 'your password will expire in 3 days')。
我试图减去 php 中的两个日期,但结果总是 return 为零,即使数据确实有价值并且当我回显日期时 return正确,但我将它们作为字符串格式存储在 wordpress 的 ACF 中。
但是数据是一样的即date_joined
加入日期值为 05/31/2016 06:33:27
日期到期值为 06/14/2016 06:33:27
<?php
$dateJoined = the_field('date_joined', $post_id );
$expiredate = the_field('expiry_date', $post_id );
//Convert them to timestamps.
$difference=(int)abs((strtotime($expiredate) - strtotime($dateJoined))/(60*60*24*30)); // 3
?>
我正在使用
检索值 $dateJoined = the_field('date_joined', $post_id );
$expiredate = the_field('expiry_date', $post_id );
这是高级自定义字段用户检索自定义字段值的方法,但如您所见,它只是 return 一个字符串
您将大约 15 天的时间戳差异除以相当于 30 天的时间戳差异,并将结果转换为整数。因此结果为 0.
对于代码中的大多数用途,以秒为单位的差异就足够了:
$difference = abs((strtotime($expiredate) - strtotime($dateJoined));
如果您需要将该值与更粗略的时间单位中的其他值进行比较,请将比较值(通过相乘)转换为秒。
仅将您的工作值转换为更粗略的单位,以便将结果呈现给用户(例如 'your password will expire in 3 days')。