c++ chrono 獲取當前時間的實現(xiàn)代碼
c++ chrono 獲取當前時間
#include <chrono>
#include <iostream>
#include <format>
namespace chrono = std::chrono;
void showCurrentMonth() {
// 獲取當前時間
chrono::time_point now{ chrono::system_clock::now() };
// 將時間轉(zhuǎn)換為year_month_day
chrono::year_month_day ymd{ chrono::floor<chrono::days>(now) };
// 獲取當前年月(類型為year_month)
chrono::year_month currentYearMonth = ymd.year() / ymd.month();
} // 獲取當月第一天
const auto firstDay = yearMonth / 1d;
// 獲取當月最后一天
const auto lastDay = chrono::year_month_day(yearMonth / chrono::last);
// 輸出格式化的標題(年份與月份)
std::string titleLine = std::format("** {:%Y-%m} **", yearMonth);
// 輸出日歷表頭(從周一到周日)
std::vector<std::string> headerLineParts;
for (const auto& weekday : Weekdays) {
headerLineParts.push_back(std::format(ZhCNLocale, "{:L%a}", weekday));
}
// 通過weekday獲取某一天是周幾
auto currentWeekday = chrono::weekday{ std::chrono::sys_days{ currentDay } };
// 通過iso_encoding獲取周幾的編碼(1-7)
auto currentWeekdayIndex = currentWeekday.iso_encoding() - 1;
// 計算本周第一天
auto firstDayOfWeek = chrono::year_month_day{ std::chrono::sys_days{ currentDay } - chrono::days(currentWeekdayIndex) }; C++標準庫用chrono獲取時間
C++有2種常用的獲取當前時間的方式。本次主要圍繞chrono展開。我的需求是,獲取當前時間,并且打印到屏幕上。然后我就使用了這個system_clock::now()
錯誤示范
#include <iostream>
#include <chrono>
using namespace std;
int main(){
auto start = std::chrono::system_clock::now();
cout<<"today is"<<start<<endl;
}使用上面這段代碼并不行!因為start沒有重載<<運算符。打印需要結(jié)合其他工具。如下:
#include <iostream>
#include <chrono>
using namespace std;
int main(){
auto start = std::chrono::system_clock::now();
std::time_t tt;
tt=std::chrono::system_clock::to_time_t(start);
string t=ctime(&tt);
cout<<"today is"<<t<<endl;
}到此這篇關(guān)于c++ chrono 獲取當前時間的文章就介紹到這了,更多相關(guān)c++ chrono 獲取當前時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++編程模板匹配超詳細的識別手寫數(shù)字實現(xiàn)示例
大家好!本篇文章是關(guān)于手寫數(shù)字識別的,接下來我將在這里記錄我的手寫數(shù)字識別的從零到有,我在這里把我自己的寫代碼過程發(fā)出來,希望能幫到和我一樣努力求知的人2021-10-10
C++?LeetCode1769移動所有球到每個盒子最小操作數(shù)示例
這篇文章主要為大家介紹了C++?LeetCode1769移動所有球到每個盒子所需最小操作數(shù)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
Dev C++編譯時運行報錯source file not compile問題
這篇文章主要介紹了Dev C++編譯時運行報錯source file not compile問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
在C++中高效使用和處理Json格式數(shù)據(jù)的示例代碼
最近的項目在用c處理后臺的數(shù)據(jù)時,因為好多外部接口都在使用Json格式作為返回的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)描述,如何在c中高效使用和處理Json格式的數(shù)據(jù)就成為了必須要解決的問題,需要的朋友可以參考下2023-11-11

