Dec 26

C语言时间函数的使用(ISO C / POSIX / SUS...) 不指定

felix021 @ 2009-12-26 18:23 [IT » 程序设计] 评论(0) , 引用(0) , 阅读(4653) | Via 本站原创 | |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#define P(a, b) printf(#b ": %" #a "\n", b)
#define Ps(a, c, b) P(a, (c)->b)
#define alloc(name, type, n) type *name = (type *) malloc(sizeof(type) * (n))
#define allocs(name, type, n) alloc(name, struct type, (n))

int main ()
{
    time_t t1 = time(NULL);
    P(ld, t1);

    struct timeval tv1;
    gettimeofday(&tv1, NULL);
    Ps(ld, &tv1, tv_sec);
    Ps(ld, &tv1, tv_usec);

    /*
     * //t1 += 8 * 3600;
     * struct tm *tm1 = gmtime(&t1); //标准时间
     */
    struct tm *tm1 = localtime(&t1); //本地时间
    Ps(d, tm1, tm_sec);
    Ps(d, tm1, tm_min);
    Ps(d, tm1, tm_hour);
    Ps(d, tm1, tm_mday);
    Ps(d, tm1, tm_mon+1); //0-based
    Ps(d, tm1, tm_year+1900); //从1900年开始, 0-based

    allocs(tm2, tm, 1);
    tm2->tm_sec = 0;
    tm2->tm_min = 0;
    tm2->tm_hour= 0;
    tm2->tm_mday= 1;
    tm2->tm_mon = 0;
    tm2->tm_year= 70;
    tm2->tm_isdst = 0;
    time_t t2 = mktime(tm2);
    //t2 += 3600 * 8; //mktime是本地时间
    P(ld, t2);

    P(s, asctime(tm1)); //标准时间
    P(s, ctime(&t1)); //本地时间

    alloc(buf, char, 100);

    strftime(buf, 100, "%Y-%m-%d %H:%M:%S", tm1); //标准时间
    P(s, buf);

    strftime(buf, 100, "%F %T", tm1); //标准时间, 格式和上面的一样
    P(s, buf);
    return 0;
}




欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]