将years.months格式的字符串转换为PHP中的月份[已关闭]

问题描述 投票:0回答:5

不幸的是,我从客户那里收到了格式不寻常的数据。我期望年份和月份在单独的列中,但相反,它以点分隔的字符串形式出现:

[years].[months]

我已将此数据导入 MySql 数据库,现在需要将

years.months
转换为
months
,我将在其上进一步设置一些操作。

所以我想仅在 PHP 中将 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
php string math time text-parsing
5个回答
3
投票

假设您的字段第一部分代表年数,第二部分代表月数。

将字段视为字符串,然后通过

.

将其分解
$yearwithdecimal = "1.2";
$months = 0;
if($yearwithdecimal){
    $parts = explode('.', $yearwithdecimal);
    $months = $parts[0]*12 + ($parts[1] ?? 0);
}
echo $months;

演示:https://3v4l.org/VhOfV


3
投票

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

0
投票
    $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;

-1
投票
  1. 将增量值分为两部分,$incYears 和 $incMonths
  2. 将 $incYears 转换为月份 ($incYears * 12) 并添加 $incMonths
  3. 将月份添加到日期
    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

-2
投票
$yearWithDecimal = 1.2;

$years = floor($yearWithDecimal);
$months = ($yearWithDecimal - $years) * 12;

$totalMonths = ($years * 12) + $months;

echo $totalMonths; // Output is 14.4
© www.soinside.com 2019 - 2024. All rights reserved.