ARM+Linux 系统时间打印函数(亲测有效)

**AT91SAM9G45系统编译过程中,有时需要系统打印时间来作为测试代码,整理下面测试方法,供大家学习参考。

#include
#include
#include
#include

/*

  • 获取系统时间,这种方式获取得到的格式是: Wed Mar 30 20:41:21 2022
    */
    int printf_time(void)
    {
    time_t timep;
    time(&timep);
    char *s = ctime(&timep);
    printf(“date:%s”,s);
    return 0;
    }

/*

  • 获取系统时间,这种方式获取得到的格式是: 2022-03-30 20:41:21.104
    */
    int get_time_ms(char buff, int len)
    {
    struct timeval tv;
    struct tm
    ptm;
    char time_string[40];
    long milliseconds;

    if(buff == NULL)
    {
    printf(“%s buff is NULL.\n”, func);
    return -1;
    }

    gettimeofday(&tv, NULL);

    ptm = localtime (&(tv.tv_sec));

    strftime (time_string, sizeof(time_string), “%Y-%m-%d %H:%M:%S”, ptm); //输出格式为: 2022-03-30 20:38:37
    milliseconds = tv.tv_usec / 1000;
    snprintf (buff, len, “%s.%03ld”, time_string, milliseconds); //输出格式为: 2022-03-30 20:38:37.182
    return 0;
    }

int main(int argc, const char **argv)
{
char buff[40];
get_time_ms(buff, sizeof(buff));
printf(“time:%s\n”, buff);
printf_time();
return 0;
}

你可能感兴趣的:(linux,运维,服务器)