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;

}

相关推荐
神奇的程序员9 小时前
从已损坏的备份中拯救数据
运维·后端·前端工程化
oden10 小时前
AI服务商切换太麻烦?一个AI Gateway搞定监控、缓存和故障转移(成本降40%)
后端·openai·api
李慕婉学姐11 小时前
【开题答辩过程】以《基于Android的出租车运行监测系统设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·后端·vue
m0_7400437311 小时前
SpringBoot05-配置文件-热加载/日志框架slf4j/接口文档工具Swagger/Knife4j
java·spring boot·后端·log4j
晨晖211 小时前
单链表逆转,c语言
c语言·数据结构·算法
招风的黑耳12 小时前
我用SpringBoot撸了一个智慧水务监控平台
java·spring boot·后端
Miss_Chenzr12 小时前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
期待のcode12 小时前
Springboot核心构建插件
java·spring boot·后端
2501_9216494912 小时前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融
serendipity_hky13 小时前
【SpringCloud | 第5篇】Seata分布式事务
分布式·后端·spring·spring cloud·seata·openfeign