从日期数计算日期?

时间:2012-11-06 00:21:46

标签: c++

如何从C ++中的日期数计算日期?我不要求你编写整个代码,我只是无法弄清楚数学来计算月份和日期!

示例:

input: 1
output: 01/01/2012

input: 10
output: 01/10/2012

input: 365
output: 12/31/2012

它总会使用当前年份,如果超过365,我会返回0.没有必要进行闰年检测。

3 个答案:

答案 0 :(得分:8)

使用日期计算库作为例如与之相关的精细Boost Date_Time

using namespace boost::gregorian;
date d(2012,Jan,1);                     // or one of the other constructors
date d2 = d + days(365);                // or your other offsets

答案 1 :(得分:1)

标准库甚至都不是很难。如果我像C程序员一样编写C ++代码(C ++ <ctime>没有可重入gmtime函数),请原谅我:

#include <time.h>
#include <cstdio>

int main(int argc, char *argv[])
{
    tm t;
    int daynum = 10;

    time_t now = time(NULL);
    gmtime_r(&now, &t);
    t.tm_sec = 0;
    t.tm_min = 0;
    t.tm_hour = 0;
    t.tm_mday = 1;
    t.tm_mon = 1;
    time_t ref = mktime(&t);
    time_t day = ref + (daynum - 1) * 86400;
    gmtime_r(&day, &t);
    std::printf("%02d/%02d/%04d\n", t.tm_mon, t.tm_mday, 1900 + t.tm_year);

    return 0;
}

很抱歉,我不知道如何在没有闰年检测的情况下执行此操作

答案 2 :(得分:1)

程序中的简单代码段,假设一年365天:

int input, day, month = 0, months[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};

while (input > 365) {
    // Parse the input to be less than or equal to 365
    input -= 365;
}

while (months[month] < input) {
    // Figure out the correct month.
    month++;
}

// Get the day thanks to the months array
day = input - months[month - 1];