获取当前时间C

我想得到我系统的当前时间。为此,我在C中使用以下代码:
time_t now;
struct tm *mytime = localtime(&now); 
if ( strftime(buffer, sizeof buffer, "%X", mytime) )
{
    printf("time1 = "%s"n", buffer);
}
问题是这段代码给出了一些随机时间。此外,随机时间每次都不同。我想要我系统的当前时间。     
已邀请:
从这里复制粘贴:
/* 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;
}
(只需将“void”添加到main()参数列表中,以便在C)中工作     
初始化你的
now
变量。
time_t now = time(0); // Get the system time
localtime
函数用于将传递的
time_t
中的时间值转换为
struct tm
,它实际上不会检索系统时间。     
简单的方法:
#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] = '';
    printf("Current Time : %sn", time_str);

    return 0;
}
    
为了扩展上面@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);
}
有关
struct tm
的更多信息,请访问此处。     
#include<stdio.h>
#include<time.h>

void main()
{
    time_t t;
    time(&t);
    printf("n current time is : %s",ctime(&t));
}
    
伙计们,您可以使用此功能获取当前的当地时间。如果你想要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);
    
#include <stdio.h>
#include <time.h>

void main()
{
    time_t t;
    time(&t);
    clrscr();

    printf("Today's date and time : %s",ctime(&t));
    getch();
}
    
伙计们,我有了新的方式获得系统时间。尽管它冗长且充满愚蠢的作品,但通过这种方式,您可以获得整数格式的系统时间。
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    char hc1,hc2,mc1,mc2;
    int hi1,hi2,mi1,mi2,hour,minute;
    system("echo %time% >time.txt");
    fp=fopen("time.txt","r");
    if(fp==NULL)
       exit(1) ;
    hc1=fgetc(fp);
    hc2=fgetc(fp);
    fgetc(fp);
    mc1=fgetc(fp);
    mc2=fgetc(fp);
    fclose(fp);
    remove("time.txt");
    hi1=hc1;
    hi2=hc2;
    mi1=mc1;
    mi2=mc2;
    hi1-=48;
    hi2-=48;
    mi1-=48;
    mi2-=48;
    hour=hi1*10+hi2;
    minute=mi1*10+mi2;
    printf("Current time is %d:%dn",hour,minute);
    return 0;
}
    

要回复问题请先登录注册