页首Html代码

返回顶部

C语言零碎记录之Linux下C语言关于时间的函数

在手册上有 time ctime  gmtime localtime asctime mktime settimeofday,gettimeofday等时间函数

还有UTC和本机时间和这些函数的区别.了解这些 是linux时间编程必须得!

首先说基本的结构体和typedef 以及define:

time_t   <time.h>

#ifndef __TIME_T
#define __TIME_T /* 避免重复定义 time_t */
typedef long time_t; /* 时间值time_t 为长整型的别名*/
#endif

使用方法是 time(&time_tvar);这样time函数会返回 且 给这个地址的time_t类型的变量赋值为一个单位为秒的值(从1970-1-1 0:0:0到现在这一秒的数目,其最大是32位(4294967296),但是没有unsigned只好一半;2011.12.22大约是1324544508,距离其饱满大约还有几十年,即使是unsigned,从1970年开始 只有132.95年,到2103年(4194288000),这个数值将溢出..汗,下次再设计的时候 希望不要再考虑 几个字节.应该尽量的大...)

对于从1970年到现在的秒,我自己也写了一个算法:

int getDaysSinceYear(){//0-365 not including this year!
time_t t;time(&t);
struct tm *p;
p=localtime(&t);
return p->tm_yday;
}


int getDaysSinceYear2(int year,int mon,int day){//这个是另外一个算法,范围1-366.所以应该-1 来达到上面的目的
int myyday=0;
mon--;//last Month and before
while(mon>0){//from 1 to last month!!!!!!!!!!
switch(mon){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:myyday+=31;break;
case 4:
case 6:
case 9:
case 11:myyday+=30;break;
case 2:myyday+=28;break;
default:break;
}
mon--;
}
myyday+=day;//And Plus this month's days
if(year%4==0)myyday+=1;// 2 yue if it is 29 days!!!
return myyday;
}

int getSecondsByTime(int year,int month,int days,int hour,int minute,int second){
//input format : 2011 11 11 11 11 11

printf("%d-%d-%d %d:%d:%d == input time\n",year,month,days,hour,minute,second);

int daySeconds=24*60*60;
seconds=hour*60*60+minute*60+second;//this year!
seconds+=(getDaysSinceYear())*daySeconds;
year--;//so not including this year!
for(;year>=1970;year--){//1970 - last year!
seconds+=365*daySeconds;
if(year%4==0)seconds+=daySeconds;
}
seconds-=8*60*60;//UTC Time .Current +8 hours beijing!
printf("%d == seconds(1970) in UTC\n",seconds);
return seconds;
}

最后获得的秒我有一个操作 :seconds-=8*60*60;为什么这么做?因为 我的电脑设置显示本地时间(即不是UTC时间)

如果按照UTC时间那需要+8个小时的.(windows上也默认是local时间,不是UTC的,所以经常出现俩时间不同步的问题,只要取消linux的UTC就可以了,在/etc/rc.conf类似的文件中设置我的是archlinux)

这个时间是从BIOS获取的,操作系统要处理这个时间,如果以UTC时间来处理,那么把BIOS时间当 UTC+0的时间,我们设置了UTC的timezone区域是 北京 UTC+8,所以linux此时就会把系统时间+8个小时就超时了...(后来我改成local时间,重启系统,时间恢复,比之前-8小时,一些文件的时间就惨了..提示 比现在靠后8小时...),所以time()是UTC+0的时间,如果系统设置UTC timezone为+0 我想就没着问题了吧...汗啊..谁叫我们的时间比他们UTC+0时区要早8个小时呢.

即使改成系统时间为BIOS本地时间,在编程他还是获得的是UTC时间,我们如果要获得当前的时间,需要-8小时.太恶心了.

从时间变成秒,linux没有直接的函数.但是从秒变成 时间的结构体就有了!!gmtime(&time_tVar)和localtime(&time_tVar);

这俩的区别就是 UTC,又是它 恶心啊...秒是当前时间的秒,UTC+0,使用gmtime获得UTC+0的时间,localtime获得本地时间UTC+8,localtime是正确的.

 现在时间就是下面的这个...还是说明 t 是UTC+0的时间.

总之这个时间编程中UTC是比较烦人的..还有一个问题是: Java 中可以获得微妙,秒后 有1000*1000的进位,如果用C来把Java的时间转换成现实时间呢???

 

 


 


 

 

 

posted @ 2011-12-22 17:31  ayanmw  阅读(2278)  评论(0编辑  收藏  举报

页脚Html代码