曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 6456|回复: 0
打印 上一主题 下一主题

时间和日期(Time and Date)

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2009-2-19 14:28:53 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
处理时间,使用一个整数类型: time_t
在 Linux 系统,这个类型被定义为长整型。time_t 在 time.h 头文件中有定义。

永远不要假设这个时间值只是32位的。在 UNIX 和 Linux 系统里,使用 32 位 time_t 类型,在到达 2038 年时,这个 time_t 就会翻滚回初始值。

通过调用 time() 函数可以得到 low-level 的时间值,这个值是从纪元(UNIX 和 Linux 系统从 1970 年开始记起)开始到现在位置的秒数。如果参数 tloc 不是个空指针的话,time() 函数也把值返回到由 tloc 指针所指向的位置。

函数原型
#include <time.h>
time_t time(time_t *tloc);

用法示例
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main()
{
        int i;
        time_t the_time;

        for(i = 1; i <= 10; i++) {
                the_time = time((time_t *)0);
                printf("The time is %ld\n", the_time);
                sleep(2);
        }

        exit(0);
}
运行结果输出
[root@localhost C]# ./envtime.exe
The time is 1235037957
The time is 1235037959
The time is 1235037961
The time is 1235037963
The time is 1235037965
The time is 1235037967
The time is 1235037969
The time is 1235037971
The time is 1235037973
The time is 1235037975

格林威治时间相关说明
http://www.groad.net/bbs/read.ph ... =1&toread=1#tpc

为了看到当地时间(local time),你需要使用 localtime() 取代 gmtime(),localtime() 函数定义如下:
#include <time.h>
struct tm *localtime(const time_t *timeval);
localtime() 函数等同于 gmtime(),除了它返回的结构体包含着本地时间区的调整值和夏令时。

若要把 tm 结构体转换回 raw time_t 值,可以使用 mktime() 函数实现:
#include <time.h>
time_t mktime(struct tm *timeptr);

对于要更友好的时间显示方式,如 date 命令的输出,在程序中可以使用 asctime() 和 ctime() 函数:
#include <time.h>
char *asctime(const struct tm *timeptr);
char *ctime(const time_t *timeval);

通过 tm 结构体指针 timeptr 得到 asctime() 函数返回的可以表示时间和日期的一个字符串。

asctime() 函数测试代码

#include <stdio.h>
#include <time.h>

int main()
{
        struct tm *timeptr;
        time_t the_time;

        time(&the_time);
        timeptr = localtime(&the_time);

        printf("%s", asctime(timeptr) );  //由于asctime()函数输出字符串时会自动换行这里就没必要再用\n

        return 0;
}

运行输出
[root@localhost C]# ./asctime.exe
Fri Feb 20 12:12:37 2009

更直接的还可以使用 ctime() 函数,示例代码:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
        time_t timeval;

        (void)time(&timeval);
        printf("The date is: %s",ctime(&timeval) );

        exit(0);
}
运行及输出
[root@localhost C]# ./ctime.exe
The date is: Fri Feb 20 12:15:45 2009

关于 strftime() 和 strptime() 两个时间函数分别见
http://www.groad.net/bbs/read.php?tid=605
http://www.groad.net/bbs/read.php?tid=606 
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-4 00:11 , Processed in 0.078462 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表