ตัวอย่างโค้ด
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t now = time(0);
char* dt = ctime(&now);
cout << "The local date and time : " << dt << endl;
return 0;
}
ผลลัพธ์
The local date and time : Wed Oct 3 08:35:24 2018
คำอธิบาย
time_t now = time(0);− ดึงเวลาปัจจุบัน (Unix Timestamp)ctime(&now)− แปลงเป็น String รูปแบบ "Day Mon DD HH:MM:SS YYYY"
รูปแบบที่ปรับแต่งได้ (C++11/20)
#include <iostream>
#include <chrono>
#include <iomanip>
int main() {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::cout << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
return 0;
}
ใช้ <chrono> และ std::put_time เพื่อจัดรูปแบบวันที่/เวลาตามต้องการ