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;

}

相关推荐
666HZ6662 小时前
C语言——高精度加法
c语言·开发语言·算法
Cosolar2 小时前
银河麒麟 / aarch64 系统:Docker + Docker Compose 完整安装教程
后端·程序员·架构
星释2 小时前
Rust 练习册 100:音乐音阶生成器
开发语言·后端·rust
kaliarch2 小时前
2025年IaC生态全景与实践指南:从工具选型到多云治理
后端·云计算·自动化运维
Coder-coco2 小时前
个人健康管理|基于springboot+vue+个人健康管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·mysql·论文
b***65322 小时前
springboot整合mybatis-plus(保姆教学) 及搭建项目
spring boot·后端·mybatis
5***E6852 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
x***01062 小时前
SpringSecurity+jwt实现权限认证功能
android·前端·后端
5***26223 小时前
Spring Boot问题总结
java·spring boot·后端
风生u3 小时前
go进阶语法
开发语言·后端·golang