
在电子商务网站中,有时需要向用户展示产品已经发布了多长时间,例如“上架x年x月x天”。然而,传统的基于时间戳的简单数学运算(如将总秒数除以固定天数来计算年、月、日)往往会因为闰年、不同月份的天数差异而导致计算结果不准确。为了解决这一问题,php 提供了强大的 datetime 和 dateinterval 类,它们能够精确地处理日期和时间之间的复杂关系。
许多开发者在计算日期差时,可能会尝试获取两个日期的 Unix 时间戳,然后计算它们的差值(秒数),再将这个秒数差值转换为年、月、日。例如:
// 错误的计算方式示例 $dateDifference = abs(strtotime($now_time) - strtotime($datetime)); $y = floor($dateDifference / (365 * 60 * 60 * 24)); // 简单地除以365天 $m = floor(($dateDifference - $y * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24)); // 简单地除以30天 // ... 这种方式无法正确处理闰年和月份天数变化
这种方法的最大问题在于,它假设一年固定为365天,一个月固定为30天。然而,实际情况是:
这些差异会导致计算结果偏离实际,尤其是在跨越多个年份或月份时,累积误差会变得明显。
PHP 的 DateTime 类提供了处理日期和时间的高级功能,包括创建日期对象、格式化日期、以及最重要的——计算日期之间的差异。DateTime::diff() 方法是解决此问题的关键,它返回一个 DateInterval 对象,该对象精确地包含了两个日期之间的年、月、日、时、分、秒等所有差异信息,并且正确处理了闰年和月份天数变化。
以下代码演示了如何在 WooCommerce 中集成此功能,使其在商品详情页和商品列表页显示产品的上架时长。
<?php
/**
* 获取产品上架时长的辅助函数
* 使用 DateTime 和 DateInterval 精确计算年、月、日
*
* @param WC_Product $product WooCommerce 产品对象
* @param string $format 可选,输出格式字符串,默认为 'years, months and days'
* @return string 格式化后的产品上架时长字符串
*/
function get_product_launch_duration_string( $product, $format = 'years, months and days' ) {
if ( ! $product instanceof WC_Product ) {
return '';
}
// 获取产品创建日期 (通常是发布日期)
// get_the_date() 获取当前文章/产品发布日期,格式化为 'd-m-Y'
$published_date_string = get_the_date( 'd-m-Y', $product->get_id() );
$published = new DateTime( $published_date_string );
// 获取当前日期
// current_time() 获取当前 WordPress 时间,格式化为 'd-m-Y'
$today = new DateTime( current_time( 'd-m-Y' ) );
// 计算日期间隔
$interval = $published->diff( $today );
$output = [];
// 根据需求构建输出字符串
if ( $interval->y > 0 ) {
$output[] = sprintf( _n( '%s year', '%s years', $interval->y, 'your-text-domain' ), $interval->y );
}
if ( $interval->m > 0 ) {
$output[] = sprintf( _n( '%s month', '%s months', $interval->m, 'your-text-domain' ), $interval->m );
}
if ( $interval->d > 0 ) {
$output[] = sprintf( _n( '%s day', '%s days', $interval->d, 'your-text-domain' ), $interval->d );
}
if ( empty( $output ) ) {
return __( 'Less than a day', 'your-text-domain' ); // 如果不足一天
}
// 根据格式要求组合字符串
switch ( $format ) {
case 'years, months and days':
// 示例: 1 year, 2 months and 3 days
$last_item = array_pop( $output );
if ( ! empty( $output ) ) {
return implode( ', ', $output ) . ' ' . __( 'and', 'your-text-domain' ) . ' ' . $last_item;
}
return $last_item;
case 'years, months':
// 示例: 1 year, 2 months
$output_ym = [];
if ( $interval->y > 0 ) {
$output_ym[] = sprintf( _n( '%s year', '%s years', $interval->y, 'your-text-domain' ), $interval->y );
}
if ( $interval->m > 0 ) {
$output_ym[] = sprintf( _n( '%s month', '%s months', $interval->m, 'your-text-domain' ), $interval->m );
}
return implode( ', ', $output_ym );
case 'simple':
// 示例: 1y 2m 3d
$simple_parts = [];
if ( $interval->y > 0 ) $simple_parts[] = $interval->y . 'y';
if ( $interval->m > 0 ) $simple_parts[] = $interval->m . 'm';
if ( $interval->d > 0 ) $simple_parts[] = $interval->d . 'd';
return implode( ' ', $simple_parts );
default:
// 默认输出所有有值的年、月、日
return implode( ', ', $output );
}
}
/**
* 在商品详情页显示产品上架时长
*/
add_action( 'woocommerce_single_product_summary', 'display_single_product_launch_time', 25 );
function display_single_product_launch_time() {
global $product; // 获取当前产品对象
$duration_string = get_product_launch_duration_string( $product );
if ( ! empty( $duration_string ) ) {
echo '<div class="product-launch-time">';
echo '<strong>' . __( 'Product Launch Date:', 'your-text-domain' ) . '</strong> ' . $duration_string;
echo '</div>';
}
}
/**
* 在商品循环列表页(如商店页、分类页)显示产品上架时长
*/
add_action( 'woocommerce_after_shop_loop_item', 'display_product_loop_launch_time', 20 );
function display_product_loop_launch_time() {
global $product; // 获取当前产品对象
// 可以在这里选择不同的格式,例如只显示年和月
$duration_string = get_product_launch_duration_string( $product, 'years, months' );
if ( ! empty( $duration_string ) ) {
echo '<div class="product-loop-launch-time">';
echo '<small>' . __( 'Launched:', 'your-text-domain' ) . ' ' . $duration_string . '</small>';
echo '</div>';
}
}
get_product_launch_duration_string( $product, $format ) 函数:
display_single_product_launch_time() 函数:
display_product_loop_launch_time() 函数:
文本域 (Text Domain):
输出格式定制:
钩子位置与优先级:
性能考量:
日期来源:
$published = $product->get_date_created(); // 返回 WC_DateTime 对象 $today = new WC_DateTime(); // 获取当前 WC_DateTime 对象 $interval = $published->diff($today);
这种方式在处理 WooCommerce 内部日期和时区时可能更具一致性。本教程的 get_the_date() 方案同样有效且简洁。
通过利用 PHP 的 DateTime 和 DateInterval 类,我们可以轻松且精确地计算出 WooCommerce 产品的上架时长。这种方法避免了手动日期计算中常见的闰年和月份天数差异问题,确保了显示结果的准确性。将这些功能集成到 WooCommerce 的适当钩子中,可以无缝地在您的产品页面和列表页展示这些有价值的信息,提升用户体验。
以上就是精确计算 WooCommerce 产品上架时长:年、月、日显示教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号