我买了一台 MacBook Pro,过去两天我一直在使用 MacOS。我一直在尝试编写使用 chrono
和 ctime
库输出日期和时间的 C++ 代码。
这段代码在我的 Windows 机器和 CentOS7 服务器上运行良好。但是,在我的 MacBook Pro 上它无法编译。
这是我尝试使用 G++ 编译时收到的错误消息:
main.cpp:19:61: error: no viable conversion from 'time_point<std::__1::chrono::steady_clock,
duration<[...], ratio<[...], 1000000000>>>' to 'const
time_point<std::__1::chrono::system_clock, duration<[...], ratio<[...], 1000000>>>'
std::time_t date = std::chrono::system_clock::to_time_t(now);
^~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/chrono:1340:28: note: candidate constructor
(the implicit copy constructor) not viable: no known conversion from
'std::__1::chrono::time_point<std::__1::chrono::steady_clock, std::__1::chrono::duration<long long,
std::__1::ratio<1, 1000000000> > >' to 'const
std::__1::chrono::time_point<std::__1::chrono::system_clock, std::__1::chrono::duration<long long,
std::__1::ratio<1, 1000000> > > &' for 1st argument
class _LIBCPP_TEMPLATE_VIS time_point
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/chrono:1340:28: note: candidate constructor
(the implicit move constructor) not viable: no known conversion from
'std::__1::chrono::time_point<std::__1::chrono::steady_clock, std::__1::chrono::duration<long long,
std::__1::ratio<1, 1000000000> > >' to 'std::__1::chrono::time_point<std::__1::chrono::system_clock,
std::__1::chrono::duration<long long, std::__1::ratio<1, 1000000> > > &&' for 1st argument
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/chrono:1359:5: note: candidate template
ignored: could not match 'std::__1::chrono::system_clock' against 'std::__1::chrono::steady_clock'
time_point(const time_point<clock, _Duration2>& t,
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/chrono:1566:53: note: passing argument to
parameter '__t' here
static time_t to_time_t (const time_point& __t) _NOEXCEPT;
^
1 error generated.
basavyr@Roberts-MacBook-Pro simpleTest %
这是代码:
void getTime()
{
auto now = std::chrono::high_resolution_clock::now();
std::time_t date = std::chrono::system_clock::to_time_t(now);
std::cout << std::ctime(&date);
}
int main()
{
getTime();
}
我认为这个问题与 MacOS 使用 CLANG 编译器有关?
任何想法我该如何解决这个问题?
谢谢!
最佳答案
您的代码只有在 std::high_resolution_clock
与 std::system_clock
的类型相同时才可能工作。无法保证来自不同时钟的时间点相同或可转换。
对于转换为只有秒分辨率的 time_t
system_clock
将完全足够:
void getTime()
{
auto now = std::chrono::system_clock::now();
std::time_t date = std::chrono::system_clock::to_time_t(now);
std::cout << std::ctime(&date);
}
int main()
{
getTime();
}
关于MacOS 上的 C++ : show date and time issue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59486190/