C中日历时间转换

日历时间转换

cpp 复制代码
#include <stdio.h>
#include <time.h>

int main()
{
   time_t timep;
   struct tm *localtmp;
   struct tm *gmtmp;
   timep = time(NULL);
   gmtmp = gmtime(&timep);
   printf("gmtmp      :%s", asctime(gmtmp));
   localtmp = localtime(&timep);
   printf("localtmp   :%s", asctime(localtmp));
   printf("ctime      :%s", ctime(&timep));

   timep = mktime(gmtmp);
   printf("gmtieme   :%ld\n",timep);
   timep = mktime(localtmp);
   printf("localtmp  :%ld\n",timep);
}

指定日期转换形式

cpp 复制代码
#include <stdio.h>
#include <time.h>
 
int main ()
{
   time_t rawtime;
   struct tm *info;
   char buffer[80];

   time(&rawtime);
   info = localtime(&rawtime);

   strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
   printf("本地时间 : |%s|\n", buffer);

   info = gmtime(&rawtime);
   strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
   printf("UTC时间  : |%s|\n", buffer);
   return (0);
}

获取时间

cpp 复制代码
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

int main(void)
{
    struct timeval tvStart, tvEnd;
    struct timespec timeStart, timeEnd;
    double fTimeInterval = 0.0;
    int i = 0;

    for (i = 0; i < 3; i++)
    {
        // --- Test gettimeofday ---
        gettimeofday(&tvStart, NULL);
        usleep(50000); // Delay for 50ms
        gettimeofday(&tvEnd, NULL);

        // Calculate elapsed time in milliseconds
        fTimeInterval = (tvEnd.tv_sec - tvStart.tv_sec) * 1000.0 +
                        (tvEnd.tv_usec - tvStart.tv_usec) * 0.001;

        printf("gettimeofday  =  %f ms\n", fTimeInterval);

        // --- Test clock_gettime ---
        clock_gettime(CLOCK_REALTIME, &timeStart);
        usleep(50000); // Delay for 50ms
        clock_gettime(CLOCK_REALTIME, &timeEnd);

        // Calculate elapsed time in milliseconds
        fTimeInterval = (timeEnd.tv_sec - timeStart.tv_sec) * 1000.0 +
                        (timeEnd.tv_nsec - timeStart.tv_nsec) * 0.000001;

        printf("clock_gettime =  %f ms\n", fTimeInterval);
    }

    return 0;
}
相关推荐
吴声子夜歌20 分钟前
正则指引——PHP
开发语言·正则表达式·php
Claire_8832 分钟前
企业文件管理系统选型技术框架与主流产品对比分析
开发语言·php
(Charon)40 分钟前
【C++】:使用 mutex + deque 实现一个简单的 LockedQueue
开发语言·c++
星轨初途1 小时前
LeetCode 热题 100——day10 和为 K 的子数组
开发语言·c++·算法·leetcode
sycmancia1 小时前
Qt——自定义控件温度计
开发语言·qt
UQR1 小时前
一、Java基础高频面试题
java·开发语言
MoonBit月兔1 小时前
MoonBit 受邀亮相 SPLASH/ISSTA 2026,与 Java、Rust、Eiffel、D 语言核心贡献者同场交流
开发语言·后端·rust
必须会一定会2 小时前
用纯 HTML/JS 做一个 AI 需求澄清器:把模糊想法转换成可执行任务书
开发语言·前端·javascript·人工智能·html·ai编程
MC皮蛋侠客2 小时前
TDengine C++ 系列(5):C/C++ 连接器——连接管理与查询 API
c语言·c++·tdengine
天空'之城2 小时前
C 语言工业级通用组件手写 27:配置参数管理组件
c语言·eeprom·参数管理·工业级组件·掉电存储