🕐 C++ 日期和时间 - L27 进阶概念

掌握time库使用、日期计算、时间格式化

📚 日期和时间概述

为什么需要日期和时间?

在程序开发中,经常需要处理日期和时间:记录日志计算时间差定时任务显示当前时间等。C++提供了ctime库来处理时间和日期。

  • 获取当前时间:系统时间戳
  • 时间格式化:转换为可读格式
  • 时间计算:计算时间差、日期加减
  • 性能测量:代码执行时间统计
  • 日志记录:带时间戳的日志
💡 时间的表示方式:
time_t:时间戳(从1970年1月1日开始的秒数)
tm结构体:分解的时间(年、月、日、时、分、秒)
字符串:格式化后的时间文本

time_t和tm结构体

#include <iostream> #include <ctime> using namespace std; int main() { // time_t:时间戳类型 time_t now = time(nullptr); cout << "当前时间戳:" << now << endl; // tm结构体:分解的时间 tm* timeinfo = localtime(&now); cout << "年份:" << (timeinfo->tm_year + 1900) << endl; cout << "月份:" << (timeinfo->tm_mon + 1) << endl; cout << "日期:" << timeinfo->tm_mday << endl; cout << "小时:" << timeinfo->tm_hour << endl; cout << "分钟:" << timeinfo->tm_min << endl; cout << "秒钟:" << timeinfo->tm_sec << endl; cout << "星期:" << timeinfo->tm_wday << endl; // 0=周日 return 0; }

tm结构体的成员

struct tm { int tm_sec; // 秒 (0-60) int tm_min; // 分 (0-59) int tm_hour; // 时 (0-23) int tm_mday; // 日 (1-31) int tm_mon; // 月 (0-11) ⚠️ 需要+1 int tm_year; // 年 (从1900开始) ⚠️ 需要+1900 int tm_wday; // 星期 (0-6, 0=周日) int tm_yday; // 一年中的第几天 (0-365) int tm_isdst; // 夏令时标志 };
⚠️ 注意事项:
• tm_mon从0开始,显示时需要+1
• tm_year从1900开始,显示时需要+1900
• tm_wday:0=周日,1=周一...6=周六

⚙️ 时间基本操作

获取和显示当前时间

#include <iostream> #include <ctime> using namespace std; int main() { // 方法1:使用ctime()直接转换为字符串 time_t now = time(nullptr); cout << "当前时间:" << ctime(&now); // 方法2:使用asctime()格式化tm结构体 tm* timeinfo = localtime(&now); cout << "格式化时间:" << asctime(timeinfo); // 方法3:手动格式化 cout << (timeinfo->tm_year + 1900) << "-"; cout << (timeinfo->tm_mon + 1) << "-"; cout << timeinfo->tm_mday << " "; cout << timeinfo->tm_hour << ":"; cout << timeinfo->tm_min << ":"; cout << timeinfo->tm_sec << endl; return 0; }

时间格式化(strftime)

#include <iostream> #include <ctime> using namespace std; int main() { time_t now = time(nullptr); tm* timeinfo = localtime(&now); // strftime:格式化时间为字符串 char buffer[80]; // 格式1:YYYY-MM-DD HH:MM:SS strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo); cout << "格式1:" << buffer << endl; // 格式2:YYYY/MM/DD strftime(buffer, sizeof(buffer), "%Y/%m/%d", timeinfo); cout << "格式2:" << buffer << endl; // 格式3:星期几 月 日 年 strftime(buffer, sizeof(buffer), "%A, %B %d, %Y", timeinfo); cout << "格式3:" << buffer << endl; // 常用格式符: // %Y - 四位年份 %m - 月份(01-12) %d - 日期(01-31) // %H - 小时(00-23) %M - 分钟 %S - 秒 // %A - 星期全称 %B - 月份全称 return 0; }

时间计算

#include <iostream> #include <ctime> using namespace std; int main() { // 计算两个时间点之间的差值 time_t start = time(nullptr); // 模拟一些操作 for (int i = 0; i < 1000000; i++) { // 空循环 } time_t end = time(nullptr); // 计算时间差(秒) double diff = difftime(end, start); cout << "执行时间:" << diff << " 秒" << endl; // 日期加减 time_t now = time(nullptr); tm* timeinfo = localtime(&now); // 7天后的日期 timeinfo->tm_mday += 7; mktime(timeinfo); // 规范化tm结构体 char buffer[80]; strftime(buffer, sizeof(buffer), "%Y-%m-%d", timeinfo); cout << "7天后:" << buffer << endl; return 0; }
🎮 互动实验:时间格式化演示

选择不同的时间格式,查看输出结果

选择格式后点击按钮...

🛠️ 常用时间函数

高精度计时(chrono库)

#include <iostream> #include <chrono> using namespace std; using namespace chrono; int main() { // 获取当前时间点 auto start = high_resolution_clock::now(); // 模拟操作 for (int i = 0; i < 1000000; i++) { // 空循环 } auto end = high_resolution_clock::now(); // 计算时间差 auto duration = duration_cast(end - start); cout << "执行时间:" << duration.count() << " 毫秒" << endl; // 其他时间单位: // nanoseconds - 纳秒 // microseconds - 微秒 // milliseconds - 毫秒 // seconds - 秒 return 0; }

睡眠和延迟

#include <iostream> #include <thread> #include <chrono> using namespace std; using namespace chrono; int main() { cout << "开始..." << endl; // 睡眠1秒 this_thread::sleep_for(seconds(1)); cout << "1秒后..." << endl; // 睡眠500毫秒 this_thread::sleep_for(milliseconds(500)); cout << "又过了0.5秒" << endl; return 0; }

实际应用:倒计时程序

#include <iostream> #include <thread> #include <chrono> using namespace std; using namespace chrono; void countdown(int seconds) { for (int i = seconds; i >= 0; i--) { cout << "\r倒计时:" << i << " 秒 "; cout.flush(); if (i > 0) { this_thread::sleep_for(seconds(1)); } } cout << "\n时间到!" << endl; } int main() { cout << "输入倒计时秒数:"; int sec; cin >> sec; countdown(sec); return 0; }

🚀 高级时间处理

计算年龄

#include <iostream> #include <ctime> using namespace std; int calculateAge(int birthYear, int birthMonth, int birthDay) { time_t now = time(nullptr); tm* currentTime = localtime(&now); int currentYear = currentTime->tm_year + 1900; int currentMonth = currentTime->tm_mon + 1; int currentDay = currentTime->tm_mday; int age = currentYear - birthYear; // 如果还没过生日,年龄减1 if (currentMonth < birthMonth || (currentMonth == birthMonth && currentDay < birthDay)) { age--; } return age; } int main() { int year, month, day; cout << "输入出生年月日(YYYY MM DD):"; cin >> year >> month >> day; int age = calculateAge(year, month, day); cout << "您的年龄是:" << age << " 岁" << endl; return 0; }

实际应用:日志系统

#include <iostream> #include <fstream> #include <ctime> #include <string> using namespace std; class Logger { private: ofstream logFile; string getCurrentTime() { time_t now = time(nullptr); tm* timeinfo = localtime(&now); char buffer[80]; strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo); return string(buffer); } public: Logger(const string& filename) { logFile.open(filename, ios::app); } void log(const string& message) { logFile << "[" << getCurrentTime() << "] " << message << endl; cout << "[" << getCurrentTime() << "] " << message << endl; } ~Logger() { logFile.close(); } }; int main() { Logger logger("app.log"); logger.log("程序启动"); logger.log("执行任务A"); logger.log("执行任务B"); logger.log("程序结束"); return 0; }

📝 实战练习

📝 理解测试

以下代码的输出是什么?

#include <iostream> #include <ctime> using namespace std; int main() { time_t now = time(nullptr); tm* timeinfo = localtime(&now); cout << timeinfo->tm_mon << endl; return 0; }
选择答案查看解析...
💻 综合挑战

题目:编写一个程序,实现以下功能:
1. 输入两个日期(年月日)
2. 计算两个日期之间相差的天数
3. 判断第一个日期是星期几
4. 输出结果

点击"生成代码框架"查看提示...