Let's say I have the following program to export an object to JSON:
struct MyChronoObject {
std::string name;
std::chrono::system_clock::time_point birthday;
MyChronoObject(const std::string name_) : name(name_) {
birthday = std::chrono::system_clock::now();
}
std::string toJSON1() {
std::string s = "{ \"name\": \"" name "\", \"birthday\": ";
s = std::to_string((birthday.time_since_epoch().count() / 1000000));
s = " }";
return s;
}
std::string toJSON2() {
std::string s = "{ \"name\": \"" name "\", \"birthday\": ";
s = std::to_string((birthday.time_since_epoch().count()));
s = " }";
return s;
}
void setBirthday(int birthday_in_seconds) {
// how do I properly cast this?
}
};
Which, for toJSON1()
, has the output { "name": "Steve", "birthday": 16687719115 }
There are several problems with this code (which I will mention but will probably address them in separate threads), but first and foremost...
- The number
16687747280
is not correct. It should be one digit shorter forseconds
or 2 digits longer formilliseconds
if I go by this: EpochConverter - Not dividing the the birthday by one million,
toJSON2()
, leads to a number that is one digit too long formicroseconds
and 2 digits too short fornanoseconds
:16687747280849928
.
So which way would be correct (and most efficient) to store and convert the stored epoch time so that I can export it to something that can be used by Javascript?
Thank you in advance!
P.S.: Other questions that I have are:
- How do I cast back a number that the
C
program receives from the frontend (like insetBirthday
)? - Should I even store the date as
chrono
object if seconds are sufficient? - How do I add exactly one year so that I land on the same date (e.g. 25.1.2019 to 25.1.2020), considering things like leap years, etc.).
- What about dates before 1970?
CodePudding user response:
duration.count()
returns a number of ticks. Not seconds, nor microseconds, nor nanoseconds. Unless the tick period happens to be 1, 10⁻⁶, or 10⁻⁹ seconds.
You have to multiply that by the period, which is given in class attributes of your duration. Which in you case, depends on the clock type (all those are templates, and the period depend on the actual class)
One way is to cast the duration into a duration whose you know the period.
Like
std::chrono::duration_cast<std::chrono::seconds>(birthday.time_since_epoch()).count()
// Instead of birthday.time_since_epoch().count()
CodePudding user response:
Note the default unit of std::chrono::system_clock
is undefined. Instead of using birthday.time_since_epoch().count() / 1000000
, you should cast the time unit to the appropriate unit for you:
std::chrono::duration_cast<std::chrono::seconds>(birthday.time_since_epoch())
.count()
This will give you the amount of second.