ไลบรารีมาตรฐาน C++ ไม่มีประเภทวันที่ที่เหมาะสม C++ สืบทอดโครงสร้างและฟังก์ชันสำหรับการจัดการวันที่และเวลาจาก C ในการเข้าถึงฟังก์ชันและโครงสร้างที่เกี่ยวข้องกับวันที่และเวลา คุณจะต้องรวมไฟล์ส่วนหัว
มีสี่ประเภทที่เกี่ยวข้องกับเวลา:clock_t, time_t, size_t และ tm ประเภท - clock_t, size_t และ time_t สามารถแสดงเวลาและวันที่ของระบบเป็นจำนวนเต็มบางประเภทได้
โครงสร้างประเภท tm ถือวันที่และเวลาในรูปแบบของโครงสร้าง C ที่มีองค์ประกอบดังต่อไปนี้ -
struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
} สมมติว่าคุณต้องการดึงข้อมูลวันที่และเวลาของระบบปัจจุบัน ไม่ว่าจะเป็นเวลาท้องถิ่นหรือเวลาสากลเชิงพิกัด (UTC) ต่อไปนี้เป็นตัวอย่างเพื่อให้บรรลุเช่นเดียวกัน –
ตัวอย่าง
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
char* dt = ctime(&now); // convert now to string form
cout << "The local date and time is: " << dt << endl;
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
} ผลลัพธ์
The local date and time is: Fri Mar 22 13:07:39 2019 The UTC date and time is:Fri Mar 22 07:37:39 2019