📄 linux_time_functions.c
字号:
// file linux_time_functions.c
//
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <sys/timeb.h>
//------------------------------------------------------------------------------------
int isleap(int year) {
// every fourth year is a leap year
// except for century years
// that are not divisible by 400
return (!(year % 4) && ((year % 100) || !(year % 400)));
}
//------------------------------------------------------------------------------------
struct tm* localtime(const time_t* gmt) {
#define SPD (24*60*60) // seconds per day
const unsigned int spm[12] = {
0,
31,
31+28,
31+28+31,
31+28+31+30,
31+28+31+30+31,
31+28+31+30+31+30,
31+28+31+30+31+30+31,
31+28+31+30+31+30+31+31,
31+28+31+30+31+30+31+31+30,
31+28+31+30+31+30+31+31+30+31,
31+28+31+30+31+30+31+31+30+31+30};
static struct tm r;
time_t t;
struct timezone tz;
long timezone;
int i;
time_t tmp;
gettimeofday(0, &tz);
timezone = tz.tz_minuteswest * 60L;
t = *gmt - timezone;
tmp = t % SPD;
r.tm_sec = tmp % 60;
tmp /= 60;
r.tm_min = tmp % 60;
r.tm_hour = tmp / 60;
tmp = t / SPD;
r.tm_wday = (4 + tmp) % 7;
for (i=1970; ; ++i) {
time_t k = isleap(i) ? 366 : 365;
if (tmp >= k) tmp -= k;
else break;
}
r.tm_year = i - 1900;
r.tm_yday = tmp;
r.tm_mday = 1;
if (isleap(i) && (tmp > 58)) {
if (tmp == 59) r.tm_mday = 2; // Feb 29
tmp -= 1;
}
for (i=11; i && (spm[i]>tmp); --i) ;
r.tm_mon = i;
r.tm_mday += tmp - spm[i];
return &r;
}
//------------------------------------------------------------------------------------
int main(void) {
struct timeb timebuffer;
struct tm *newtime;
struct timeval tv;
ftime(&timebuffer);
printf("timebuffer.time = %08X timebuffer.millitm = %3d \n",
timebuffer.time, timebuffer.millitm);
gettimeofday(&tv, 0);
printf(" tv.tv_sec = %08X tv.tv_msec = %3d \n",
tv.tv_sec, tv.tv_usec/1000);
// newtime = localtime(&timebuffer.time);
newtime = localtime(&tv.tv_sec);
printf("%d ", newtime->tm_year);
printf("%d ", newtime->tm_mon);
printf("%d ", newtime->tm_mday);
printf("%d ", newtime->tm_hour);
printf("%d ", newtime->tm_min);
printf("%d\n", newtime->tm_sec);
}
//------------------------------------------------------------------------------------
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -