1 获取时间和日期
运行着的程序获得时间或日期是很有意义的,所有的类UNIX系统都使用同一个时间和日期的起点,即格林尼治时间(GMT)1970年1月1日,这被称为UNIX纪元的起点,时间从那时经过的秒数来衡量。MS—DOS纪元始于1980年。
在Linux中处理时间的函数及时间类型在头文件<time_t>
中定义。
#include <time.h>
time_t time(time_t* tloc);
double difftime(time_t time1,time_t time2);
struct tm* gmtime(const time_t timeval);
time函数获取底层时间值,返回从纪元开始的秒数,time_t在32位Linux系统上是32位长的,时间将在2038年回绕。
difftime函数计算time1-time2的值。
gmtime函数把底层时间值分解为一个结构,包含一些常用的成员,返回UTC时间,所以该时间与北京时间并不相同。这样做是为了同步全球所使用的程序和系统,使不同时区的系统在同一时刻创建的文件具有相同的创建时间。
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
time_t the_time;
for(int i = 0;i < 10;i++)
{
the_time = time((time_t*)0);
printf("the time is %ld\n",the_time);
sleep(2);
}
exit(0);
}
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct tm* tm_ptr;
time_t the_time;
time(&the_time);
tm_ptr = gmtime(&the_time);
printf("Raw time is %ld\n",the_time);
printf("data:%02d/%02d/%02d\n",tm_ptr->tm_year,tm_ptr->tm_mon + 1,tm_ptr->tm_mday);
printf("time:%02d/%02d/%02d\n",tm_ptr->tm_hour,tm_ptr->tm_min,tm_ptr->tm_sec);
exit(0);
}
在这里我们看到获取的时间比北京时间早了8个小时,因为北京在东八区(UTC+8),而
gmtime返回的是世界标准时间,即格林尼治时间。
#include <time.h>
struct tm* localtime(const time_t* timeval);
time_t mktime(struct tm* timeptr);
char* asctime(const struct tm* timeptr);
char* ctime(const time_t* timeval);
localtime返回的结构指针中保存的是本地时区的时间.
mktime将已分解的tm结构合成为原始的time_t时间值,失败返回-1。
asctime返回一个长度固定为26个字符的固定格式字符串。
ctime返回的是本时区的固定格式字符串。
#include <time.h>
size_t strftime(char*s,size_t maxsize,const char* format,struct tm* timeptr);
char* strptime(const char* buf,const char* format,struct tm* timeptr);
strftime函数格式化timeptr指针指向的结构,按照format给定的格式,字符串被指定至少maxsize个字符长,将结果放在字符串s中。
strptime函数读取字符串并创建tm结构,返回一个指针,指向转换处理过程最后一个字符后面的那个字符,调用程序需要检查是否已从传递的字符串中读取了足够的数据。
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
struct tm* tmptr;
struct tm timestruct;
time_t the_time;
char buf[256];
time(&the_time);
tmptr = localtime(&the_time);
strftime(buf,256,"%A %d %B,%I:%S %p",tmptr);
printf("strftime gives: %s\n",buf);
strcpy(buf,"Thu 26 July 2007,17:53 will do fine");
printf("calling strptime with: %s\n",buf);
tmptr = ×truct;
char* result = strptime(buf,"%a %d %b %Y,%I:%S",tmptr);
printf("strptime consumed up to: %s\n",result);
printf("strptime gives:\n");
printf("date: %02d/%02d/%02d\n",tmptr->tm_year % 100,tmptr->tm_mon + 1,tmptr->tm_mday);
printf("time: %02d:%02d\n",tmptr->tm_hour,tmptr->tm_min);
exit(0);
}