มีหลายวิธีในการพิมพ์วัน วันที่ และเวลาของระบบในรูปแบบที่มนุษย์อ่านได้
วิธีแรก
ใช้เวลา() − ใช้สำหรับค้นหาเวลาตามปฏิทินปัจจุบันและมีประเภทข้อมูลเลขคณิตที่เก็บเวลา
เวลาท้องถิ่น() − ใช้สำหรับเติมโครงสร้างด้วยวันที่และเวลา
asctime() − แปลงเวลาท้องถิ่นเป็นรูปแบบที่มนุษย์อ่านได้
วัน เดือน วันที่ ชั่วโมง:เดือน:สอง ปี
ตัวอย่าง
#include<iostream>
#include<ctime> // used to work with date and time
using namespace std;
int main() {
time_t t; // t passed as argument in function time()
struct tm * tt; // decalring variable for localtime()
time (&t); //passing argument to time()
tt = localtime(&t);
cout << "Current Day, Date and Time is = "<< asctime(tt);
return 0;
} ผลลัพธ์
หากเรารันโปรแกรมข้างต้น มันจะสร้างผลลัพธ์ดังต่อไปนี้
Current Day, Date and Time is = Tue Jul 23 19:05:50 2019
วิธีที่สอง
ไลบรารี Chrono ใช้เพื่อวัดเวลาที่ผ่านไปในหน่วยวินาที มิลลิวินาที ไมโครวินาที และนาโนวินาที
ตัวอย่าง
#include <chrono>
#include <ctime>
#include <iostream>
Using namespace std;
int main() {
auto givemetime = chrono::system_clock::to_time_t(chrono::system_clock::now());
cout << ctime(&givemetime) << endl;
} ผลลัพธ์
หากเรารันโปรแกรมข้างต้น มันจะสร้างผลลัพธ์ดังต่อไปนี้
Current Day, Date and Time is = Tue Jul 23 19:05:50 2019
วิธีที่สาม
ตัวอย่าง
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
time_t givemetime = time(NULL);
printf("%s", ctime(&givemetime)); //ctime() returns given time
return 0;
} ผลลัพธ์
หากเรารันโปรแกรมข้างต้น มันจะสร้างผลลัพธ์ดังต่อไปนี้
Tue Jul 23 20:14:42 2019