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?