欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > C语言获取当前时间

C语言获取当前时间

2025/7/6 12:33:11 来源:https://blog.csdn.net/w11111xxxl/article/details/140244469  浏览:    关键词:C语言获取当前时间

一共有两段代码,一个是获取当前时间,一个是获取到现在的总毫秒数 求关注😄 互粉必回

获取当前时间

#include <stdio.h>

#include <time.h>

int main() {

    time_t rawtime;

    struct tm * timeinfo;

    char buffer[20];

    // 获取当前时间

    time(&rawtime);

    timeinfo = localtime(&rawtime);

    // 使用 strftime 来格式化时间

    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);

    // 输出格式化后的时间

    printf("当前时间是: %s\n", buffer);

    return 0;

}

获取到现在的总毫秒数

#include <stdio.h>

#include <sys/time.h>

#include <time.h>

int main() {

    struct timeval tv;

    struct tm *now;

    long total_milliseconds;

    // 获取当前时间

    gettimeofday(&tv, NULL);

    // 将时间戳转换为可读的tm结构体

    now = localtime(&tv.tv_sec);

    // 计算总毫秒数

    total_milliseconds = (now->tm_year + 1900) * 31536000000L; // 一年大约有31536000000毫秒

    total_milliseconds += (now->tm_mon + 1) * 2628000000L; // 一个月大约有2628000000毫秒

    total_milliseconds += now->tm_mday * 86400000L; // 一天有86400000毫秒

    total_milliseconds += now->tm_hour * 3600000L; // 一小时有3600000毫秒

    total_milliseconds += now->tm_min * 60000L; // 一分钟有60000毫秒

    total_milliseconds += now->tm_sec * 1000L; // 一秒有1000毫秒

    total_milliseconds += tv.tv_usec / 1000; // 将微秒转换为毫秒

    // 输出总毫秒数

    printf("总毫秒数: %ld\n", total_milliseconds);

    return 0;

}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词