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;

}

相关推荐
·云扬·2 分钟前
SpringBoot
java·spring boot·后端
电商数据girl2 小时前
B2C电商接口解决方案||搭建电商项目必备电商接口
java·大数据·开发语言·人工智能·后端·json
EterNity_TiMe_2 小时前
【C语言进阶】C语言动态内存管理:深入理解malloc、calloc与realloc
c语言·开发语言·学习·visualstudio·性能优化·学习方法
wxy20243152 小时前
连年(年份)
c语言·c++·算法
一叶之秋14123 小时前
内存魔术师:精通内存函数的艺术
c语言
会敲代码的小张3 小时前
设计模式-外观模式
java·开发语言·后端·设计模式·外观模式
知星小度S3 小时前
数据结构——栈和队列
c语言·数据结构·算法·链表
2401_857636394 小时前
医护人员排班系统:Spring Boot技术的应用策略
java·spring boot·后端
q567315234 小时前
Django 文件上传时出现 500 错误
开发语言·数据库·后端·python·django·sqlite
鹿屿二向箔4 小时前
C语言实现一个简单的点歌系统
c语言·开发语言