1

我有以下格式的月份

2012-01
2012-02
2012-03
2012-04
2012-05
2012-06

月份存储在 varchar 中(我只想存储月份)。我想知道如何将当前的 Ym 与数据库中的月份一起减去并返回月份?

Eg: (2012-11) - (2012-06) = 5
4

3 回答 3

2

如果您只想要几个月,那将是一个数字……为什么要使用 varchar?int 会更适合。

但由于它是 varchar,只需使用字符串操作,而不是丑陋的数学:

month = RIGHT(yourvalue, 2)

例如...- 2012-11>11

于 2012-11-14T14:35:55.940 回答
2

我想已经有日期计算的解决方案了。但是对于您的简单任务,这可能会让我矫枉过正。

如果您只想要月份的结果,我建议您仅将日期转换为月份。

$year   = substr($string,  0, 4);   // first four digits
$month  = substr($string, -2);      // last two digits
$months = $year * 12 + $month;

然后您可以轻松地减去两个日期,结果将是月份的偏移量。

$offset = $months1 - $months2;

在您的示例中,这将计算以下内容。

$string1 = "2012-11";
$string2 = "2012-06";
$year1   = substr($string1,  0, 4); // 2012
$year2   = substr($string2,  0, 4); // 2012
$month1  = substr($string1, -2);    // 11
$month2  = substr($string2, -2);    // 06
$months1 = $year1 * 12 + $month1;   // 24155
$months2 = $year2 * 12 + $month2;   // 24150
$offset  = $months1 - $months2;     // 5

这是一个执行您的任务的简单 php 函数。

function months($string)
{
    if(strlen($string) < 6) return; // just to be sure
    return substr($string, 0, 4) * 12 + substr($string, -2);
}

function offset($minuend, $subtrahend)
{
    return months($minuend) - months($subtrahend);
}

echo offset("2012-11", "2012-06");  // output "5"
于 2012-11-14T14:36:10.140 回答
1
<?php

function getMonthCount($date) {
    $parts = explode('-', $date);
    return ($parts[0] * 12) + $parts[1];
}

$first  = '2012-11';
$second = '2012-06';
echo getMonthCount($first) - getMonthCount($second);
于 2012-11-14T14:41:18.300 回答