簡體   English   中英

如何使用 Chrono 或 ctime libaray 輸入設定的開始和結束時間

[英]How can I input a set start and end time using Chrono or ctime libaray

我很難理解 c++ 的時間。 我想像這樣輸入時間值。

time_t  t = time(0);
tm* now = localtime(&t);
cin >> now->tm_wday >> now->tm_mon >> now->tm_year;

我覺得這是一種錯誤的做法。 我的主要目標是嘗試創建開始時間和日期以及結束時間和日期,並讓 object 運行到給定的結束時間和日期。 輸入時間值讓我感到困惑,並希望得到一些幫助,引導我朝着正確的方向前進。

std::localtime返回的std::tm*不是存儲數據的好地方。請注意, std::tm結構中的所有不同偏移量都有很好的記錄

僅使用年、月和工作日是不夠的。 例如,每個月有不止一天有星期六。

你可以這樣做:

#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>

int main() {
    std::tm now{}; // declare and initialize your own tm
    std::chrono::system_clock::time_point cc;

    std::cout << "enter\nyear month day\n";

    std::cin >> now.tm_year >> now.tm_mon >> now.tm_mday;

    // compensate for offsets
    now.tm_year -= 1900;
    now.tm_mon -= 1;

    // convert to std::time_t
    std::time_t n = std::mktime(&now);

    // here you get a chrono time_point from the user input
    cc = std::chrono::system_clock::from_time_t(n);

    // convert back to std::time_t
    n = std::chrono::system_clock::to_time_t(cc);

    // print the result
    std::cout << std::put_time(std::localtime(&n), "%FT%T") << "\n";
}

示例輸入/輸出:

enter
year month day
2019 11 20
2019-11-20T00:00:00

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM