得到减去当前Y-m后的月数

时间:2012-11-14 14:32:03

标签: php mysql sql

我有以下格式的月份

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

月份存储在varchar中(我只想存储月份)。我想知道如何减去当前的Y-m以及数据库中的月份并返回月份?

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

3 个答案:

答案 0 :(得分:2)

如果你只想要几个月,这就是一个数字...为什么要使用varchar? int会更适合。

但是因为它是varchar,所以只使用字符串操作,而不是丑陋的数学:

month = RIGHT(yourvalue, 2)

例如.... 2012-11 - > 11

答案 1 :(得分: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"

答案 2 :(得分: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);