Mic*_*urr 31
在POSIX中,time_t值被指定为秒,但是C标准不能保证这一点,因此在非POSIX系统上可能不是这样.它通常是(事实上,我不确定它不是一个代表秒数的值).
下面是一个time_t使用标准库工具添加时间值的示例,该时间值不假设表示秒数,这对于操作时间来说真的不是特别好:
#include <time.h>
#include <stdio.h>
int main()
{
time_t now = time( NULL);
struct tm now_tm = *localtime( &now);
struct tm then_tm = now_tm;
then_tm.tm_sec += 50; // add 50 seconds to the time
mktime( &then_tm); // normalize it
printf( "%s\n", asctime( &now_tm));
printf( "%s\n", asctime( &then_tm));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
将时间字符串解析为适当的struct tm变量留作练习.该strftime()函数可用于格式化一个新strptime()函数(POSIX 函数可以帮助解析).
小智 7
C日期/时间类型time_t实现为自特定日期以来的秒数,因此要向其添加秒数,您只需使用常规算术.如果这不是您要问的问题,请让您的问题更清楚.
使用来自的类型和功能<time.h>.
time_t now = time(0);
time_t now_plus_50_seconds = now + 50;
time_t now_plus_2_hours = now + 7200;
Run Code Online (Sandbox Code Playgroud)
<time.h>声明处理time_t和struct tm类型的函数.这些功能可以做你想做的一切.
| 归档时间: |
|
| 查看次数: |
24911 次 |
| 最近记录: |