how to declare and define a time data?
I have a class that needs to contain a time variable. How to do that? I would like to specify that I communicate with a server and as a response at time section I receive for example: 2011-07-01T14:32:39+02:00 .APPRECIATE. THX
P.S I would like to use th开发者_如何学编程e C++ API.
Go for boost::posix_time::ptime
if you can use boost, because this is easy to use.
#include <boost/date_time/posix_time/posix_time.hpp>
using boost::posix_time;
// local time with second precision
ptime currentTime(second_clock::localtime());
// UTC time with second precision
ptime currentTime(second_clock::universal_time());
// local time with microsecond precision
ptime currentTime(microsec_clock::localtime());
// UTC time with microsecond precision
ptime currentTime(microsec_clock::universal_time());
For strings you can use the following
std::string s = "2011-08-25 23:59:59.000";
// get ptime from a string
ptime t = time_from_string(s);
// get string from ptime
std::string s = to_simple_string(currentTime);
For more information, take a look at the docs.
There are several solutions each with another drawback. One would be to just calculate the timestamp and save it as a number. Another would be to use boost date_time (which I would prefer if you can introduce a dependency to boost). It all very much depends on what you need to do with the time. If you only need to save it and don't need to do calculations on it, may be even a std::string would be good enough. If you need to do very simple operations on it, a timestamp is probably good enough and the simplest way (however you still have the burden to parse it). For complex stuff boost would be my preferred way to go.
You can use the tm
struct for holding the time data.
I recently went old school in my otherwise pretty modern C++ project and used sscanf
to parse the incoming data strings (from RSS, ATOM), because I didn't want to depend on any OS-specific framework (the app is for Cocoa Touch and Windows) nor introduce Boost dependency. And it performs really great, as always.
精彩评论