localtime函数的奇怪行为

Strange behaviour of localtime function

本文关键字:函数 localtime      更新时间:2023-10-16

我试图从当前日期减去7天,并将它们发送到一个函数。我的代码是:

time_t startTime;
time_t endTime;
struct tm *startDate;
struct tm *endDate;
time(&endTime);
endDate = localtime(&endTime); //here endDate becomes 26-05-2015
startTime = endTime - 24 * 60 * 60 * 7;
startDate = localtime(&startTime);

但是在此之后endDate和startDate都变成19-05-2015

我哪里错了?

允许localtime为字符串使用内部(static)缓冲区,这意味着您需要复制返回的字符串,或者使用localtime_s代替。

std::localtime()函数返回一个指向静态struct的指针,因此每次返回相同的地址。

你可以像这样复制std::localtime()的返回值:

#include <ctime>
int main()
{
    time_t startTime;
    time_t endTime;
    // don't use pointers
    std::tm startDate;
    std::tm endDate;
    time(&endTime);
    // dereference the return value (with *) to make a copy
    endDate = *std::localtime(&endTime); 
    startTime = endTime - 24 * 60 * 60 * 7;
    startDate = *std::localtime(&startTime);
}

它们都是指向同一结构体的指针。声明您自己的struct tm变量并复制localtime()返回值指向的内容:

struct tm startDate, endDate;
....
endDate   = * localtime(&endTime);
....
startDate = * localtime(&startTime);