Linux--获取当前时间

一、说明: Linux内部对时间是用从Epoch时间开始计时的秒数来表示的。Epoch也就是通用协调时间(UTC,也就是格林尼治平均时间或格林威治标准时间,CMT)。Linux将这个数据存储在time_t结构体变量里。

二、用到的函数:time()&localtime()函数

1.  time() 函数

/*  time - 获取计算机系统当前的日历时间(Calender Time)
 *         处理日期时间的函数都是以本函数的返回值为基础进行运算
 *
 *  函数原型:
 *      #include <time.h>
 *  
 *      time_t time(time_t *calptr);
 *
 *  返回值:
 *      成功:秒数,从1970-1-1,00:00:00
 *
 *  使用:
 *      time_t now;
 *  
 *      time(&now); // == now = time(NULL);
 */
 2.  localtime() 函数
/*
 *  localtime - 将时间数值变换成本地时间,考虑到本地时区和夏令时标志
 *
 *  函数声明:
 *      #include <time.h>
 *
 *      struct tm * localtime(const time_t *timer);
 *
 */

/*  struct tm 结构
 *
 *  此结构体空间由内核自动分配,而且不需要去释放它
 */ 
struct tm {
    int tm_sec;     /*秒,    范围从0到59 */
    int tm_min;     /*分,    范围从0到59 */
    int tm_hour;    /*小时,  范围从0到23 */
    int tm_mday;    /*一个月中的第几天,范围从1到31 */
    int tm_mon;     /*月份,  范围从0到11 */
    int tm_year;    /*自 1900起的年数 */
    int tm_wday;    /*一周中的第几天,范围从0到6 */
    int tm_yday;    /*一年中的第几天,范围从0到365 */
    int tm_isdst;   /*夏令时 */
}; 

3、编程:
main.c文件

// 测试代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /*related to tm struct */
#include <sys/time.h>
#include <string.h>

int main()
{
   time_t current_time;
	struct tm *current;
	char time_data[32] = "";
	char *ptr = NULL;//avoid Null pointer
	ptr = time_data;

	time(&current_time);
	
	current = localtime(&current_time);	
	//时间转换
	sprintf(time_data,"%04d-%02d-%02d-%02d:02%d:%02d",current->tm_year+1900,current->tm_mon+1,current->tm_mday,current->tm_hour,current->tm_min,current->tm_sec);
	printf("Current time is:%s",ptr+1);
   
    return 0;
}

生成time.c模块,方便调用:

#include <stdio.h>
#include <stdlib.h>
#include <time.h> /*related to tm struct */
#include <sys/time.h>
#include <string.h>

/*get time*/
char *get_current_time()//返回指针
{
	time_t current_time;
	struct tm *current;
	char time_data[32] = "";
	char *ptr = NULL;//avoid Null pointer
	ptr = time_data;

	time(&current_time);
	
	current = localtime(&current_time);	
	sprintf(time_data,"%d-%d-%d-%d:%d:%d",current->tm_year+1900,current->tm_mon+1,current->tm_mday,current->tm_hour,current->tm_min,current->tm_sec);
	return (strcpy(ptr,time_data));	
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值