Chinaunix

标题: linux 下时间函数.... [打印本页]

作者: ruchong    时间: 2010-03-15 15:09
标题: linux 下时间函数....
linux c下有现成的将时间转换成秒的函数吗...
例如: 2010-10-15 18:34:35  转换成秒.........

多谢............
作者: rain_fish    时间: 2010-03-15 15:10
asctime
作者: empty141    时间: 2010-03-15 15:16
mktime
作者: rain_fish    时间: 2010-03-15 15:18
#include <time.h>

       char *asctime(const struct tm *tm);
       char *asctime_r(const struct tm *tm, char *buf);

       char *ctime(const time_t *timep);
       char *ctime_r(const time_t *timep, char *buf);

       struct tm *gmtime(const time_t *timep);
       struct tm *gmtime_r(const time_t *timep, struct tm *result);

       struct tm *localtime(const time_t *timep);
       struct tm *localtime_r(const time_t *timep, struct tm *result);

       time_t mktime(struct tm *tm);
作者: ruchong    时间: 2010-03-15 15:18
我只要转换, 当前系统时间不能改变........
作者: zx_wing    时间: 2010-03-15 15:24
我只要转换, 当前系统时间不能改变........
ruchong 发表于 2010-03-15 15:18



    楼上给你贴的都是转换用的。不过Ctime系列函数已经过时,strftime使用格式化的方法,是Ctime系列函数的替代。
    man strftime
作者: happy_fish100    时间: 2010-03-15 15:33
回复 1# ruchong

没有现成的函数,需要自己实现。把年月日等各个字段拆分开,然后使用mktime这个函数。
作者: ruchong    时间: 2010-03-15 15:50
谢谢大家. 大家帮忙看一下哪个地方出问题了......
int main()
{
    struct tm t;
    t.tm_sec = 1;
    t.tm_min = 30;
    t.tm_hour = 9;
    t.tm_mday = 22;
    t.tm_mon = 11;
    t.tm_year = 2010;
    time_t ti = mktime(&t);
    if(-1 == ti)
    {
        printf("error = %s\n", strerror(errno));
        printf("ti = %ld\n", ti);
    }
}

输出:
localhost test # ./a.out
error = Success
ti = -1
作者: empty141    时间: 2010-03-15 16:14
tm_year        //指1900年开始经过的时间
所以应该用2010-1900吧
作者: happy_fish100    时间: 2010-03-15 16:24
tm_year        //指1900年开始经过的时间
所以应该用2010-1900吧
empty141 发表于 2010-03-15 16:14


楼上正解。
tm_year中的年份等于实际年份 - 1900,月份tm_mon等于实际月份 - 1
作者: lengyuex    时间: 2010-03-15 16:45
都是高手啊,呵呵 。
作者: ruchong    时间: 2010-03-16 11:29
非常感谢.........




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2