获取C中的当前时间

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)中工作

  • 我知道它可能有点晚了你现在可能已经想出来了,但你会使用[`strptime`](http://pubs.opengroup.org/onlinepubs/7908799/xsh/strptime.html)函数[time.h](http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html)将`char*`转换为`struct tm` (6认同)
  • 上面的代码是多余的.asctime(localtime(&rawtime))相当于单个ctime(&rawtime)函数调用. (4认同)
  • 仅供参考 - 您不需要*“time_t”对象作为“time()”的参数。将“NULL”、“0”等作为参数可以返回当前时间。 (2认同)

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)

  • 如果没有 `#include &lt;string.h&gt;` 将无法编译 (2认同)

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)


Sha*_*ikh 6

伙计们,您可以使用此功能获取当前的当地时间.如果你想要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)