gpt4 book ai didi

c++ - 在 C++ 中获取当前年份的更优雅的方式

转载 作者:行者123 更新时间:2023-11-28 04:09:19 24 4
gpt4 key购买 nike

我是 C++ 的新手。我需要获取当前年份并将其存储在一个整数中。

我已经找到了这个解决方案:

std::time_t result = std::time(nullptr);
std::istringstream iss(ctime(&result));

iss.ignore(20);
int year;
iss >> year;

我觉得这个解决方案有点难看,即使它有效,因为它看起来不是很健壮,而且需要很多步骤才能完成。

还有更好的方法吗?

最佳答案

C++20,你可以使用 std::chrono 来达到这个目的。

P0355R7 Extending to Calendars and Time Zones

#include <iostream>
#include <format>
#include <chrono>
int main()
{
const auto now = std::chrono::system_clock::now();
std::cout << std::format("{:%Y}", now); // => 2021
}

关于c++ - 在 C++ 中获取当前年份的更优雅的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58151350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com