Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

พิมพ์เวลาระบบ (System Time) ใน C++

C++ Standard Library ไม่มี date type ที่เหมาะสม C++ สืบทอด structs และฟังก์ชันสำหรับจัดการวันที่และเวลาจาก C เพื่อเข้าถึงฟังก์ชันและโครงสร้างเกี่ยวกับวันที่และเวลา คุณต้อง include เฮดเดอร์ <ctime> ในโปรแกรม C++

มี 4 ประเภทที่เกี่ยวกับเวลา: clock_t, time_t, size_t, และ tm ประเภท clock_t, size_t และ time_t สามารถแสดง system time และ date เป็นรูปแบบ integer ได้

โครงสร้าง tm เก็บวันที่และเวลาในรูปแบบ C structure ที่มีสมาชิกดังนี้:

struct tm {
    int tm_sec;   // วินาที 0-61
    int tm_min;   // นาที 0-59
    int tm_hour;  // ชั่วโมง 0-24
    int tm_mday;  // วันของเดือน 1-31
    int tm_mon;   // เดือน 0-11
    int tm_year;  // ปี นับจาก 1900
    int tm_wday;  // วันนับจากอาทิตย์
    int tm_yday;  // วันนับจาก 1 มกราคม
    int tm_isdst; // daylight savings time
}

หากต้องการดึงวันที่และเวลาปัจจุบันของระบบ ไม่ว่าจะเป็น local time หรือ UTC ตัวอย่างต่อไปนี้จะแสดงวิธีทำ:

ตัวอย่างโค้ด

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    // วันที่/เวลาปัจจุบันจากระบบ
    time_t now = time(0);
    char* dt = ctime(&now); // แปลง now เป็น string
    cout << "The local date and time is: " << dt << endl;
    
    // แปลง now เป็น tm struct สำหรับ 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