Linux C编程:获取当前的系统时间
获取当前的系统时间是挺有用的,比如说在进行软件调试,或者是软件运行需要获取当前的时间用于运行日志的编写。在Linux中与系统时间相关的函数以及数据类型定义在系统的头文件<time.h>中,在进行获取系统时间的程序的编写的时候主要运用到以下几个函数:
函数名 | 注释 |
---|---|
time() | 该函数返回的结果是从1970年1月1日0时0分0秒(一般是)到当前时间的秒数。 |
localtime() | 该函数可将time()返回的time_t类型数据转化为当前系统的真实时间,并将该转化结果返回。 |
strftime() | 该函数用于根据区域设置格式化本地时间/日期进行时间格式化,或者说格式化一个时间字符串 |
在使用strftime时间格式化函数所涉及的相关参数的含义如下:
参数 | 含义 |
---|---|
%F | 将时间格式化为年-月-日 |
%T | 将时间格式化为显示时分秒:hh:mm:ss |
%Y | 将时间格式化为带世纪部分的十制年份 |
%m | 将时间格式化为十进制表示的月份 |
%d | 将时间格式化为十进制的每月中的第几天 |
%H | 将时间格式化为24小时制的小时 |
%M | 将时间格式化为十进制表示的分钟数 |
%S | 将时间格式化为十进制表示的秒数 |
更多参数的解析可参考度娘百科:strftime的介绍。
定义时间变量相关的数据类型释义:
数据类型 | 含义 |
---|---|
time_t | 在C中,time_t是表示一个长整型数据,用于表示从1970年1月1日0时0分0秒(一般是)到当前时间的秒数 |
让我们找找该头文件的源文件中的相关定义吧,首先看看<time.h>头文件在哪,使用whereis 命令进行文件的查找:
whereis time.h
结果如下:
在该头文件中,结构体 tm中包含年月日时分秒等有关时间的基本的信息。
/* Used by other time functions. */
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
# ifdef __USE_MISC
long int tm_gmtoff; /* Seconds east of UTC. */
const char *tm_zone; /* Timezone abbreviation. */
# else
long int __tm_gmtoff; /* Seconds east of UTC. */
const char *__tm_zone; /* Timezone abbreviation. */
# endif
};
实际应用相关函数进行编程,实现在Linux中获取当前的系统时间,并以YYYY-MM-dd hh:mm:ss 的格式进行输出。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
char* getNowtime(void)
{
static char s[30]={0};
char YMD[15] = {0};
char HMS[10] = {0};
time_t current_time;
struct tm* now_time;
char *cur_time = (char *)malloc(21*sizeof(char));
time(¤t_time);
now_time = localtime(¤t_time);
strftime(YMD, sizeof(YMD), "%F ", now_time);
strftime(HMS, sizeof(HMS), "%T", now_time);
strncat(cur_time, YMD, 11);
strncat(cur_time, HMS, 8);
printf("\nCurrent time: %s\n\n", cur_time);
memcpy(s, cur_time, strlen(cur_time)+1);
free(cur_time);
cur_time = NULL;
return s;
}
int main(void)
{
getNowtime();
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/116993.html