不幸的是,我从客户那里收到了格式不寻常的数据。我期望年份和月份在单独的列中,但它以点分隔的字符串形式出现:
[years].[months]
。
我只想将 年(小数点后有月份) 转换为 月。
测试用例:
1.2
(1 年零 2 个月)至 14
1.0
(1 年 0 个月)至 12
我编写了以下可能有问题的代码,因此我想更正它。
$yearwithdecimal = "1.2";
$yearwithdecimal = (float)$yearwithdecimal;
if (is_float($yearwithdecimal)) {
$yearsArray = explode(".",$yearwithdecimal);
$year_months = $yearsArray[0]*12;
$more_months = $yearsArray[1];
$total_months = $year_months + $more_months;
}else{
$total_months = $yearwithdecimal*12;
}
echo $total_months; die;
// Output is 14
假设您的字段第一部分代表年数,第二部分代表月数。
将字段视为字符串,然后通过
.
将其分解
$yearwithdecimal = "1.2";
$months = 0;
if($yearwithdecimal){
$parts = explode('.', $yearwithdecimal);
$months = $parts[0]*12 + ($parts[1] ?? 0);
}
echo $months;
如PHP 将分钟+秒转换为秒所示,将格式化/分隔字符串解析为整数类型变量,然后将
$months
值增加 $years
值乘以 12
。
代码:(演示)
$tests = ['1.2', '1.0', '2.11'];
foreach ($tests as $test) {
sscanf($test, '%d.%d', $years, $months);
$months += $years * 12;
echo $months . PHP_EOL;
}
输出:
14
12
35
$yearwithdecimal = "1.2";
$yearwithdecimal = (float)$yearwithdecimal;
if (is_float($yearwithdecimal)) {
$yearsArray = explode(".",$yearwithdecimal);
$year_months = $yearsArray[0]*12;
$more_months = isset($yearsArray[1]) ? $yearsArray[1] : 0;
$total_months = $year_months + $more_months;
}else{
$total_months = $yearwithdecimal*12;
}
echo $total_months;
您可以在 php 中使用
round()
。
$years = 1.2;
$months = round($years * 12);
echo $months.' Months'; //14 Months
*不太准确。
function addDecimalYears($fromDate, $increment){
$segments = explode(".", (string)$increment, 2);
$incYears = isset($segments[0]) ? $segments[0] : 0;
$incMonths = isset($segments[1]) ? $segments[1] : 0;
$months = 12 * (int)$incYears;
$months += (int)$incMonths;
$fromDateTimestamp = strtotime($fromDate);
return date("Y-m-d", strtotime("+" . $months . "month", $fromDateTimestamp));
}
echo addDecimalYears("2023-11-02", 1.0) . "\n";
echo addDecimalYears("2023-11-02", 1.) . "\n";
echo addDecimalYears("2023-11-02", .12) . "\n";
echo addDecimalYears("2023-11-02", 1.6) . "\n";
echo addDecimalYears("2023-11-02", .18) . "\n";
echo addDecimalYears("2023-11-02", 0.6) . "\n";
输出:
2024-11-02
2024-11-02
2024-11-02
2025-05-02
2025-05-02
2024-05-02
$yearWithDecimal = 1.2;
$years = floor($yearWithDecimal);
$months = ($yearWithDecimal - $years) * 12;
$totalMonths = ($years * 12) + $months;
echo $totalMonths; // Output is 14.4