温馨提示×

c语言如何获取系统时间

小亿
222
2024-03-22 20:14:55
栏目: 编程语言
C语言开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在C语言中获取系统时间,可以使用 <time.h> 头文件中的函数。以下是一些获取系统时间的常用函数:

  1. time() 函数:返回当前时间(从1970年1月1日开始的秒数)。
#include <stdio.h>
#include <time.h>

int main() {
    time_t currentTime;
    time(&currentTime);
    
    printf("Current time: %ld\n", currentTime);
    
    return 0;
}
  1. ctime() 函数:将时间(从1970年1月1日开始的秒数)转换成字符串形式。
#include <stdio.h>
#include <time.h>

int main() {
    time_t currentTime;
    time(&currentTime);
    
    printf("Current time: %s", ctime(&currentTime));
    
    return 0;
}
  1. gmtime() 函数:将时间(从1970年1月1日开始的秒数)转换成 struct tm 结构体,表示UTC时间。
#include <stdio.h>
#include <time.h>

int main() {
    time_t currentTime;
    struct tm *timeinfo;
    
    time(&currentTime);
    timeinfo = gmtime(&currentTime);
    
    printf("Current UTC time: %d-%d-%d %d:%d:%d\n", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
    
    return 0;
}

这些函数可以帮助你在C语言中获取系统时间,并进行相应的操作。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:C语言怎么获取当前系统时间

0