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;
}
相关推荐
LDR00612 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术12 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园12 天前
C++20 Modules 模块详解
java·开发语言·spring
swordbob12 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享12 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Luminous.12 天前
C语言--day30
c语言·开发语言
玖玥拾12 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
何以解忧,唯有..12 天前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
謓泽12 天前
C语言不是语法,是通往机器的地图。
c语言·开发语言
云水一下12 天前
从零开始学 PHP 系列(一):PHP 的前世今生与开发环境搭建
开发语言·php