C语言如何获取本地时间,然后取时、分、秒的值?

分别取时、分、秒的数值,这个数值用于下一步操作的。

比如现在时间是 19:42
那么 我怎么才能获得42这个秒数值呢?
秒数值42要赋值给P用的
P=42

P用于下一个函数的。

C语言有2个获取时间的函数,分别是time()和localtime(),time()函数返回unix时间戳-即从1970年1月1日0:00开始所经过得秒数,而localtime()函数则是将这个秒数转化为当地的具体时间(年月日时分秒)

这里时间转化要用到一个“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代表一月) - 取值区间为[0,11] */

int tm_year;     /* 年份,其值等于实际年份减去1900 */

int tm_wday;    /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一 */

int tm_yday;    /* 从每年1月1日开始的天数– 取值区间[0,365],其中0代表1月1日 */

int tm_isdst;    /* 夏令时标识符,夏令时tm_isdst为正;不实行夏令时tm_isdst为0 */    

};

示例代码:

#include<stdio.h>

#include<time.h>

int getTime()

{

time_t t;                   //保存unix时间戳的变量 ,长整型

struct tm* lt;           //保存当地具体时间的变量

int p;                       

time(&t);                // 等价于 t =time(NULL);获取时间戳

lt = localtime(&t);  //转化为当地时间

p = lt->tm_sec;     //将秒数赋值给p

return p;

}

应该就是这样啦~

追问

为什么我的软件没有时间函数啊! 识别不了time_t

追答

time_t包含在头文件里,你看看你有没有添加#include头文件

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-07-27

#include <stdio.h>

#include <time.h>

int main()

{time_t timep;

struct tm *tp;

time(&timep);

int p;

tp = localtime(&timep); //取得系统时间

printf("Today is %d-%d-%d\n", (1900 + tp->tm_year), (1 + tp->tm_mon), tp->tm_mday);

printf("Now is %d:%02d:%02d\n", tp->tm_hour, tp->tm_min, tp->tm_sec);

p=tp->tm_sec;

printf("p=%d\n",p);

return 0;

}

追问

识别不了time_t 怎么回事啊
头文件
#include
#include
都没用啊
我用的是 Psoc Designer 5.4,请问这个C软件没有时间函数的吗?

本回答被网友采纳
第2个回答  2019-07-27

#include
#include
int main()
{char wday[][4]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
time_t timep;
struct tm *p;
time(&timep);
p = localtime(&timep); //取得系统时间
printf("Today is %s %d-%d-%d\n", wday[p->tm_wday], (1900 + p->tm_year), (1 + p->tm_mon), p->tm_mday);
printf("Now is %d:%02d:%02d\n", p->tm_hour, p->tm_min, p->tm_sec);
system("pause");
return 0;
}

追问

我的time_t 无法识别,咋回事

追答

你把time_t改为long试试?

第3个回答  2019-07-29

#include <stdio.h>

#include <time.h>

/* In <time.h>

struct tm

{

...

int tm_hour;    // 小时

int tm_min;    // 分钟

int tm_sec;    // 秒数

...

};

*/

int main()    // 主函数

{

int P;

time_t tNow;    // 声明

time(&tNow);    // 获取时间戳

struct tm* sysLocal;    // 声明

sysLocal = localtime(&tNow);    // 本地化时间(我们是UTC+8时)

P = sysLocal->tm_sec;    //     加粗体可以是其它值(tm_hour/tm_min/...)

printf("%d", P);    // 输出

return 0;    // 结束

}

提醒一句——xx:xx后面的xx是分钟,xx:xx.xx中.后面的xx才是秒数

第4个回答  2019-07-26
#include<stdio.h>
#include<time.h>
int main()
{
time_t t = time(NULL);
struct tm *info = localtime(&t);
printf("现在是:");
printf("%d年%02d月%02d日 ", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday);
printf("%02d:%02d:%02d", info->tm_hour, info->tm_min, info->tm_sec);
return 0;
}追问

秒数的值呢?P怎么提取这个值
t=tm.tm_sec;
P=t;
这样可以吗?

追答

如果你认真读了上面的程序,并且具有基本的C语言知识,你应该已经知道年月日时分秒这六个值分别怎么取。

追问

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

头文件也加了,

不行啊,根本无法识别time_t

相似回答