C++ 数学与时间
有人知道如何用ctime做数学吗?我需要能够以秒为单位获得“time_t”(就像它通常做的那样)中的时间,然后从中减去设定的秒数,然后再将time_t输入ctime以获得时间和日期 因此,基本上它会计算出这么多秒前的日期。您可以尝试:C++ 数学与时间,c++,datetime,ctime,C++,Datetime,Ctime,有人知道如何用ctime做数学吗?我需要能够以秒为单位获得“time_t”(就像它通常做的那样)中的时间,然后从中减去设定的秒数,然后再将time_t输入ctime以获得时间和日期 因此,基本上它会计算出这么多秒前的日期。您可以尝试: time_t now = time( NULL); struct tm now_tm = *localtime( &now); now_tm.tm_sec -= 50; // subtract 50 seconds to the time now_tm
time_t now = time( NULL);
struct tm now_tm = *localtime( &now);
now_tm.tm_sec -= 50; // subtract 50 seconds to the time
now_tm.tm_sec +=1000; // add 1000 sec to the time
printf( "%s\n", asctime( &now_tm));
时间是一种积分类型。它始终表示秒数,因此您可以自由地从中添加/减去整数 例如:
time_t now = time(nullptr);
time_t one_minute_ago = now - 60;
std::cout << ctime(&one_minute_ago) << std::endl;
time\u t now=时间(nullptr);
一分钟前的时间=现在-60;
std::cout时间
日期和时间的最基本表示形式是time\t类型。time_t变量的值是自1970年1月1日以来的秒数,有时称为Unix历元。这是在内部表示事件开始和结束时间的最佳方式,因为比较这些值很容易。
struct tm
虽然time_t将日期和时间表示为单个数字,但struct tm将其表示为包含大量数字的结构:
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
};
转换
可以使用localtime函数将时间值转换为struct tm值:
struct tm startTM;
time_t start;
/* ... */
startTM = *localtime(&start);
所以,你可以像这样减去设定的秒数
startTm.tm_sec -= somesecond;
struct tm startTM;
time_t start;
/* ... */
start = mktime(&startTM);
添加转换为时间\u t如下所示
startTm.tm_sec -= somesecond;
struct tm startTM;
time_t start;
/* ... */
start = mktime(&startTM);
并使用ctime fun转换日期
ctime(&start)
希望能有所帮助 我认为时间通常代表秒数,但并非总是时间应该是一种抽象,但实际上总是秒数,现在通常是64位。