Linux 时间函数

时间类型:

Coordinated Universal Time(UTC):

世界标准时间,也就是大家所熟悉的格林威治标准时间(Greenwich Mean Time, GMT)

Calender Time:

日历时间,是用一个标准时间点到此时经过的秒数来表示时间。


时间获取:

time_t time(time_t *tloc)

获取日历时间,即从1970年1月1日0点到现在所经历的秒数

struct tm *gmtime(const time_t *timep)

将日历时间转化为格林威治时间,并保存在TM 结构

struct tm *localtime(const time_t *timep)

将日历时间转化为本地时间,并保存至TM结构

int gettimeofday(struct timeval *tv, struct timezone *tz)

获取从今天0点到现在的时间差,常用于计算事件的耗时


时间显示:

char *asctime(const struct tm *tm)

将tm格式的时间转化为字符串

char *ctime(const time_t *timep)

将日历时间转化为本地时间的字符串格式 


相关结构体:

struct timeval {
int tv_sec; //秒数
int tv_usec; //微秒数

}


struct tm {
"tm_sec" - 秒数
"tm_min" - 分钟数
"tm_hour" - 小时
"tm_mday" - 月份中的第几日
"tm_mon" - 年份中的第几个月,从 0 开始表示一月
"tm_year" - 年份,从 1900 开始
"tm_wday" - 星期中的第几天
"tm_yday" - 一年中的第几天
"tm_isdst" - 夏令时当前是否生效
}


样例:

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

int main(void)
{
	struct tm *local;
	time_t t;

	t = time(NULL);
	local = localtime(&t);
	printf("Local hour is: %d\n",local->tm_hour);
	printf("%d\n", local);

	local = gmtime(&t);
	printf("UTC hour is: %d\n", local->tm_hour);
	printf(asctime(local));
        printf(ctime(&t));
	return 0;
}
结果:

Local hour is: 14

1074972032

UTC hour is: 6

Mon Aug  8 06:16:52 2011

Mon Aug  8 14:16:52 2011


struct timeval time_ts;

unsigned long long ts = 0LL;

gettimeofday(&time_ts,NULL);

ts = time_ts.tv_sec*1000000 + time_ts.tv_usec;

printf("time_ts = %lld\n", ts);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值