Ant*_*met 89 c time time-t localtime
我想得到我系统的当前时间.为此,我在C中使用以下代码:
time_t now;
struct tm *mytime = localtime(&now);
if ( strftime(buffer, sizeof buffer, "%X", mytime) )
{
printf("time1 = \"%s\"\n", buffer);
}
Run Code Online (Sandbox Code Playgroud)
问题是这段代码给出了一些随机时间.此外,随机时间每次都不同.我想要我系统的当前时间.
min*_*gos 116
从这里复制粘贴:
/* localtime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(只需将"void"添加到main()参数列表中,以便在C)中工作
Eri*_*rik 65
初始化now
变量.
time_t now = time(0); // Get the system time
Run Code Online (Sandbox Code Playgroud)
该localtime
函数用于将传递的时间值转换time_t
为a struct tm
,它实际上并不检索系统时间.
zis*_*han 34
简单的方法:
#include <time.h>
#include <stdio.h>
int main(void)
{
time_t mytime = time(NULL);
char * time_str = ctime(&mytime);
time_str[strlen(time_str)-1] = '\0';
printf("Current Time : %s\n", time_str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
hex*_*ter 12
为了扩展上面@mingos的答案,我编写了下面的函数来将我的时间格式化为特定的格式([dd mm yyyy hh:mm:ss]).
// Store the formatted string of time in the output
void format_time(char *output){
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
sprintf(output, "[%d %d %d %d:%d:%d]",timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
}
Run Code Online (Sandbox Code Playgroud)
更多相关信息struct tm
,可以发现在这里.
小智 9
#include<stdio.h>
#include<time.h>
void main()
{
time_t t;
time(&t);
printf("\n current time is : %s",ctime(&t));
}
Run Code Online (Sandbox Code Playgroud)
伙计们,您可以使用此功能获取当前的当地时间.如果你想要gmtime然后使用gmtime函数而不是localtime.干杯
time_t my_time;
struct tm * timeinfo;
time (&my_time);
timeinfo = localtime (&my_time);
CCLog("year->%d",timeinfo->tm_year+1900);
CCLog("month->%d",timeinfo->tm_mon+1);
CCLog("date->%d",timeinfo->tm_mday);
CCLog("hour->%d",timeinfo->tm_hour);
CCLog("minutes->%d",timeinfo->tm_min);
CCLog("seconds->%d",timeinfo->tm_sec);
Run Code Online (Sandbox Code Playgroud)