linux下用time(NULL)函数和localtime()获取当前时间的方法
(编辑:jimmy 日期: 2025/10/24 浏览:3 次 )
time(); 函数
函数原型: time_t time(time_t *timer)
函数用途: 得到机器的日历时间或者设置日历时间
头 文 件: time.h
输入参数: timer=NULL时,得到机器日历时间, =时间数值时 用于设置日历时间;
time_t是一个long类型
/* 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); */
localtime();函数
函数原型: struct tm *localtime(const time_t *timer)
函数用途: 返回一个以tm结构表达的机器时间信息
头 文 件: time.h
输入参数: timer:使用time()函数获得的机器时间;
/* * localtime - 将时间数值变换成本地时间,考虑到本地时区和夏令时标志 * * 函数声明: * #include <time.h> * * struct tm * localtime(const time_t *timer); * */
//结构tm的定义为:
struct tm
{
int tm_sec; /* Seconds: 0-59 (K&R says 0-61"htmlcode">
/*
* time();
* @author 李政 <1244109467@qq.com>
*/
#include <time.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
struct tm *tp;
time_t t = time(NULL);
tp = localtime(&t);
printf("%d/%d/%d\n",tp->tm_mon+1,tp->tm_mday,tp->tm_year+1900);
printf("%d:%d:%d\n",tp->tm_hour,tp->tm_min,tp->tm_sec);
return 0;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:详解apache配置域名的坑