C++ 日期时间类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1267219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ DateTime class
提问by sivabudh
I have my own C++ DateTime
class defined as:
我有自己的 C++DateTime
类定义为:
class DateTime
{
public:
int year;
int month;
int day;
int hour;
int min;
int sec;
int millisec;
};
I have 2 DateTime
which I need to compare to see which one is greater than (more recent) the other.
我有 2 个DateTime
,我需要比较一下,看看哪个比(最近的)另一个大。
Is there any freely available C++ DateTime
class that I can use to
是否有任何免费可用的 C++DateTime
类可供我使用
- Convert my DateTime class to their DateTime class
- Their class should provide < , > , <= , >= operators for comparison
- 将我的 DateTime 类转换为它们的 DateTime 类
- 他们的类应该提供 < 、 > 、 <= 、 >= 运算符进行比较
If a concrete example could be provided that would be great. Note that I need to compare down to millisecond.
如果可以提供一个具体的例子,那就太好了。请注意,我需要比较到毫秒。
I was thinking about Boostor Qt. Preferred Boostthough.
我在考虑Boost或Qt。虽然首选Boost。
回答by Fred Larson
请参阅提升日期时间库
And your class looks very much like struct tm
你的班级看起来很像struct tm
EDIT: You're right that struct tm doesn't support millisecond precision.
编辑:你是对的 struct tm 不支持毫秒精度。
Take a look at a Boost example. Does that help?
看一个Boost 示例。这有帮助吗?
回答by Gunther Piez
You may want to check out QDateTimefrom Qt, wich has the required operators and ms accuracy.
您可能想从 Qt 中查看QDateTime,它具有所需的运算符和毫秒精度。
Conversion from your class could be done via
从您的班级转换可以通过
class DateTime
{
public:
int year;
int month;
int day;
int hour;
int min;
int sec;
int millisec;
QDateTime toQDateTime() {
return QDateTime(QDate(year, month, day), QTime(hour, min, sec, millisec));
}
};
The other way around is similar ;-)
另一种方式是类似的;-)
回答by Roger Nelson
I ditch storing dates in gregorian ages ago. I store dates as an 32bit integer (sort of like a Julian date). So the date is composed as (Year * 1000) + DOY (DOY is day of year). I.e. - 2009001 Is Jan 1 2009 - 2009365 is Dec 31 2009
我在很久以前就放弃了用格里高利来存储日期。我将日期存储为 32 位整数(有点像儒略日期)。所以日期组成为 (Year * 1000) + DOY(DOY 是一年中的某一天)。即 - 2009001 是 2009 年 1 月 1 日 - 2009365 是 2009 年 12 月 31 日
My date class of course provides methods for getting the Year, Month and Day, adding, subtracting, incrementing and decrementing, comparing, getting the number of days between dates etc..
我的日期课程当然提供了获取年、月和日、加、减、递增和递减、比较、获取日期之间的天数等的方法。
For date and time, I use 64bit float where the integer portion of the real number is the same as integer (Julian like) dates described above, and the fraction represents the time in fraction of a day.
对于日期和时间,我使用 64 位浮点数,其中实数的整数部分与上述整数(类似儒略)日期相同,分数代表一天中的分数。
I.e.
IE
- 2009001.04166666666~ is Jan 1,2009 1:00am
- 2009001.06249999999~ is Jan 1,2009 1:30am
- 2009001.95833333333~ is Jan 1,2009 11:00pm
- 2009001.04166666666~ 是2009年1月1日凌晨1点
- 2009001.06249999999~ 是2009年1月1日凌晨1:30
- 2009001.95833333333~ 是2009年1月1日11:00pm
If you only need minute accuracy, you can use 32bit float for date and time but you can't adequately accurately store seconds and milliseconds.
如果您只需要分钟精度,您可以使用 32 位浮点数来表示日期和时间,但您不能充分准确地存储秒和毫秒。
The advantages of storing dates (and time) in this manner are:
以这种方式存储日期(和时间)的优点是:
You only need 8bytes to represent the data and time as compared to 28bytes (assuming 32bit integers) used by the DateTime class in the question.
Compared with dates stored as seconds from an epoch, when looking at the number (for example in the debugger) you can more or less identify from the number the year and the day of year, and the approximate time of day (to get the hour, minute, second after midnight simply mulitply by 24, 1440, 86400 respectively).
Comparing dates is trivial, simply compare the numbers (A single CPU operation compared to the several it would take for the example DateTime).
Fewer comparison operations to do date arithmetic.
与问题中 DateTime 类使用的 28 字节(假设为 32 位整数)相比,您只需要 8 字节来表示数据和时间。
与存储为纪元秒数的日期相比,在查看数字时(例如在调试器中),您可以或多或少地从数字中识别年份和年份中的日期,以及一天中的大致时间(以获得小时、分钟、午夜后的秒分别简单地乘以 24、1440、86400)。
比较日期是微不足道的,只需比较数字(单个 CPU 操作与示例 DateTime 所需的多个操作相比)。
进行日期算术的比较操作较少。
The disadvange of this (for time time) is a slight loss of accuracy (this is practically a mute point) and you have to do some simple rounding to get nice integer values when convering to integer values of hours minutes and seconds.
这样做的缺点(对于时间时间)是准确性的轻微损失(这实际上是一个静音点),并且在转换为小时分钟和秒的整数值时,您必须进行一些简单的四舍五入以获得不错的整数值。
回答by pauldoo
I don't know of any off the top of my head. But I'd consider rewriting your date class to hold a single 64-bit integer describing milliseconds since the conventional epoch (1970 is it?). Then you are free to simply divide by 1000 and use the normal CRT functions for formatting as a string, plus you can take the value modulo 1000 to get the millisecond part.
我不知道我的头顶上有什么。但我会考虑重写你的日期类来保存一个 64 位整数,描述自传统时代以来的毫秒数(是 1970 年吗?)。然后你可以自由地简单地除以 1000 并使用普通的 CRT 函数将其格式化为字符串,另外你可以取模 1000 的值来获得毫秒部分。
Comparison operators then become easy..
然后比较运算符变得容易..
回答by sivabudh
Okay, here's the final code snippet that answers my own question. I thought of sharing this in case it might helpful to some other people in the future. Thanks to Fred Larson for pointing the Boost example.
好的,这是回答我自己问题的最终代码片段。我想分享这个以防将来对其他人有所帮助。感谢 Fred Larson 指出 Boost 示例。
I chose Boost to do the DateTime calculation because my application already makes use of Boost somewhere else. I think I might have been able to use Qt as well, though I cant completely confirm.
我选择 Boost 来进行 DateTime 计算,因为我的应用程序已经在其他地方使用了 Boost。我想我也可以使用 Qt,尽管我不能完全确认。
Assuming DateTime is defined as:
假设 DateTime 定义为:
class DateTime
{
public:
int year;
int month;
int day;
int hour;
int min;
int sec;
int millisec;
};
To do a simple DateTime comparison
做一个简单的 DateTime 比较
bool DateTime::operator < (const DateTime& dt_)
{
using namespace boost::posix_time;
using namespace boost::gregorian;
ptime thisTime( date(this->year,this->month,this->day),
hours(this->hour) +
minutes(this->min) +
seconds(this->sec) +
boost::posix_time::millisec(int(this->millisec)) );
ptime thatTime( date(dt_.year,dt_.month,dt_.day),
hours(dt_.hour) +
minutes(dt_.min) +
seconds(dt_.sec) +
boost::posix_time::millisec(int(dt_.millisec)) );
return thisTime < thatTime;
}
To add 2 DateTime together to return a new DateTime
将 2 个 DateTime 相加以返回一个新的 DateTime
DateTime DateTime::operator + ( const DateTime& dt_ )
{
using namespace boost::posix_time;
using namespace boost::gregorian;
date thisDate( this->year, this->month, this->day );
date newDate = thisDate + years(dt_.year) + months(dt_.month) + days(dt_.day);
ptime newDateTime( newDate,
hours(this->hour) + hours(dt_.hour) +
minutes(this->min) + minutes(dt_.min) +
seconds(this->sec) + seconds(dt_.sec) +
boost::posix_time::millisec(int(this->millisec)) +
boost::posix_time::millisec(int(dt_.millisec))
);
DateTime dateTime;
date t1_date = newDateTime.date();
dateTime.year = t1_date.year();
dateTime.month = t1_date.month();
dateTime.day = t1_date.day();
time_duration t1_time = newDateTime.time_of_day();
dateTime.hour = t1_time.hours();
dateTime.min = t1_time.minutes();
dateTime.sec = t1_time.seconds();
dateTime.millisec = t1_time.fractional_seconds()/1000.0f;
return dateTime;
}
回答by AProgrammer
What's wrong with using the content of <time.h>
for implementing your class? It's standard C90.
使用 的内容<time.h>
来实现你的类有什么问题?这是标准的C90。
回答by Dirk Eddelbuettel
GNU R uses a struct tm replacement with microsecond precision -- instead of (integer) seconds since the epoch, it now uses a floating point number. That is really really useful. For many of my applications, I just past doubles around and yet get the time conversions. See R-2.9.1/src/main/datetime.c in the current R sources.
GNU R 使用具有微秒精度的 struct tm 替换——而不是自纪元以来的(整数)秒,它现在使用浮点数。这真的非常有用。对于我的许多应用程序,我只是过去了双打,但仍然获得了时间转换。请参阅当前 R 源中的 R-2.9.1/src/main/datetime.c。
Having that in a standalone C++ class would be handy though.
不过,在独立的 C++ 类中使用它会很方便。
回答by Learner
Look at MFC datetime classes CTime and COleDateTime classes More at http://www.codeproject.com/KB/datetime/datetimedisc.aspx
查看 MFC 日期时间类 CTime 和 COleDateTime 类 更多信息请访问http://www.codeproject.com/KB/datetime/datetimedisc.aspx