Coming from C# it was quite common for me to write a class that might have a DateTime as a return type (or parameter). Now I’m programming in C++. What is the appropriate data type to use as a method return value returning a datetime value (time_t, tm struct, Boost.Date_Time, something else?) E.g.:
class Customer
{
...
? GetDateTimeCreated() const;
void SetLastContactDateTime(? date);
...
}
Also, what about accepting date/times as function parameters?
If you’re writing a library, and the datetime value will exposed via the API, then I’d use
time_tso that users of the library are not forced to use Boost.As was pointed out,
struct tmis used for formatting atime_t. You don’t normally want to be passing those around.If your program already uses Boost, and you like the convenience of Boost.DateTime, then by all means use Boost.DateTime. If I remember correctly,
boost::posix_time::ptimeis just a wrapper around two 64-bit integers, so it’s lightweight enough to pass around by value.If you’re using C++11 features, then you might want to use
std::chrono::time_pointfrom<chrono>. If you’re still on C++03, you can use Boost.Chrono, which aims to implement the C++11 time facilities. By using Boost.Chrono, you should be able to more easily make the switch to C++11 in the future. Chrono doesn’t have as many features as Boost.DateTime, but it’s a step up from plain oldtime_t.If you need sub-second precision, then Boost.DateTime or Chrono is the way to go.