WooCommerce产品上架年月日时长显示代码日期偏差修复求助
问题原因
你现有代码的计算偏差来自timestamp_to_array函数的固定值换算逻辑:硬编码每年365天、每月30天做时间戳切割,没有处理闰年、不同月份实际天数的差异,自然会出现数日误差。
修复方案
直接使用PHP DateTime 类自带的diff()方法计算日期间隔,该方法会自动处理闰年、大小月、时区差异等场景,无需手动计算时间戳。替换你原有代码中的get_product_published_time函数,删除不再使用的timestamp_to_array函数即可生效,钩子部分无需改动:
// 计算产品上架时长 function get_product_published_time( $product ) { $datetime = $product->get_date_created(); $timezone = $datetime->getTimezone(); $now_time = new WC_DateTime(); $now_time->setTimezone($timezone); // 调用diff方法计算准确间隔,自动处理闰年、大小月 $interval = $now_time->diff($datetime); $y = $interval->y; $m = $interval->m; $d = $interval->d; return sprintf( '<div class="Joined-time">' . __('Length of Service: %s, %s and %s', 'woocommerce') . '</small></div>', $y . ' ' . _n( 'year', 'years', $y, 'woocommerce' ) , $m . ' ' . _n( 'month', 'months', $m, 'woocommerce' ) , $d . ' ' . _n( 'day', 'days', $d, 'woocommerce' ) ); } // 店铺列表页展示上架时长 add_action('woocommerce_after_shop_loop_item','dislay_product_loop_published_time', 20 ); function dislay_product_loop_published_time() { global $product; echo get_product_published_time( $product ); } // 商品详情页展示上架时长 add_action( 'woocommerce_single_product_summary', 'dislay_single_product_published_time', 25 ); function dislay_single_product_published_time() { global $product; echo get_product_published_time( $product ); }
内容的提问来源于stack exchange,提问作者PartlySunny
相关产品推荐
相关产品推荐

