在 C++ 中列印系統時間(3 種不同的方式)
有許多種方法可以將系統日期、時間以人類可讀的格式打印出來。
第一種方法
使用 time() − 它用於獲取當前日曆時間,並具有儲存時間的算術資料型別
localtime() − 它用於使用日期和時間填充結構
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP