C++ 中日期和时间的面向对象表示
我正在为嵌入式 Linux 系统编写 C++ 代码。传统上,在 Linux 上,将通过调用库函数 gettimeofday()
来检索日期和时间。但对我来说,这感觉不太面向对象。我希望能够编写与此类似的代码:
DateTime now = new DateTime;
DateTime duration = new DateTime(2300, DateTime.MILLISECONDS)
DateTime deadline = now + duration;
while(now < deadline){
DoSomething();
delete now;
now = new DateTime()
}
其中有一个 DateTime
类,它可以用当前时间或特定时间构造,并且提供成员函数甚至重载运算符对表示的日期和时间执行操作。
C++ 标准库提供类似的东西吗?我无法在目标系统上使用 Boost 库。但是,我可以考虑移植一些简单的东西(例如,仅使用头文件实现的东西)。
I am writing C++ code for an embedded Linux system. Traditionally, on Linux, the date and time would be retrieved by calling the library function gettimeofday()
. But that doesn't feel very object-oriented to me. I would like to instead be able to write code similar to this:
DateTime now = new DateTime;
DateTime duration = new DateTime(2300, DateTime.MILLISECONDS)
DateTime deadline = now + duration;
while(now < deadline){
DoSomething();
delete now;
now = new DateTime()
}
where there is a DateTime
class, which can be constructed with the current time or a particular time, and which offers member functions or even overloaded operators to perform operations on the represented date and time.
Is there something like this offered by the C++ standard libraries? I cannot use the Boost libraries on my target system. However, I could consider porting something simple (something implemented with header files only, for example).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
标准 C++ 库中没有用于处理时间和间隔的面向对象接口。
您可能想看看 Boost.Date_Time 。 Boost 非常有用并且编写得很好,它实际上是标准 C++ 库的一部分。
There is no object-oriented interface for dealing with time and intervals that's part of the standard C++ library.
You might want to look at Boost.Date_Time though. Boost is so useful and well written that its practically a part of the standard C++ library.
所以移植增强不是我的目标的一个选择。相反,我不得不使用 gettimeofday()。然而,sys/time.h 中有一些很好的宏用于处理 timeval 结构,
但我花了一段时间才找到它们,因为它们不在我的机器上的手册页中。请参阅此页面:
http://linux.die.net/man/3/timercmp
So porting boost wasn't an option for my target. Instead I had to go with gettimeofday(). There are however some nice macros for dealing with timeval structs in
sys/time.h
It took a while to find them though because they weren't in the man pages on my machine. See this page:
http://linux.die.net/man/3/timercmp
我认为你应该可以使用 ctime 中的东西来
以一种非常便携的方式完成这项工作。
cplusplus.com
I think you should be fine with using stuff from ctime
should do the job in a very portable way.
cplusplus.com
给出结构:-
在 Linux 上,也许你可以使用它......
gives structure :-
on Linux, may be you could use it...