std::chrono -> Java's LocalDate, LocalDateTime and ZonedDateTime
Channel
C++Weekly
Topics
A video about std::chrono. How to build something like Java's LocalDate, LocalDateTime and ZonedDateTime.
Length
10-20 minutes
It's so confusing...
I just want
void java() {
LocalDateTime localDateTime = LocalDateTime.now();
localDateTime = localDateTime.minusDays(1);
boolean b = localDateTime.isBefore(localDateTime);
int y = localDateTime.getYear();
int m = localDateTime.getMonthValue();
int d = localDateTime.getDayOfMonth();
System.out.println(localDateTime);
}
But how??
void cpp() {
using LocalDateTime = std::chrono::local_time<std::chrono::system_clock::duration>;
LocalDateTime localDateTime = std::chrono::system_clock::now(); // ?? broken
localDateTime -= std::chrono::days{1};
bool b = localDateTime < localDateTime;
int y = localDateTime.year(); // ?? broken
int m = localDateTime.month(); // ?? broken
int d = localDateTime.day(); // ?? broken
std::println("{}", localDateTime);
}
Is there any useful 'LocalDateTime' / 'LocalDate' type in c++?
More confusion...
int main() {
using LocalDate = std::chrono::year_month_day;
LocalDate today; // how to get the current date?
today.year();
today.month();
today.day();
bool bd = today < today;
today += std::chrono::days{1}; // broken
std::println("{}", today);
// --------
using LocalTime = std::chrono::hh_mm_ss<std::chrono::system_clock::duration>;
LocalTime now; // how to get the current time?
now.hours();
now.minutes();
now.seconds();
now.subseconds();
bool bt = now < now; // broken
now += std::chrono::seconds{1}; // broken
std::println("{}", now);
}
If we remove the broken parts and compile and run the output is
32739-00-00 is not a valid date
00:00:00.000000
lol - how to use that suff??
Here we go...
#include <boost/date_time/posix_time/posix_time.hpp>
#include <print>
int main() {
using namespace boost::posix_time;
auto now = microsec_clock::local_time();
auto d = now.date().day();
auto mo = now.date().month();
auto y = now.date().year();
auto h = now.time_of_day().hours();
auto mi = now.time_of_day().minutes();
auto s = now.time_of_day().seconds();
auto b = now < now;
now += seconds{1};
std::println("{}", to_iso_extended_string(now));
}
But it's boost::date_time. And std::chrono ??
Hmm
#include <chrono>
#include <print>
int main() {
using namespace std::chrono;
time_point now {system_clock::now()};
now += seconds{1};
bool b = now < now;
year_month_day date {floor<days>(now)};
auto d = date.day();
auto mo = date.month();
auto y = date.year();
hh_mm_ss time {now - floor<days>(now)};
auto h = time.hours();
auto mi = time.minutes();
auto s = time.seconds();
auto ms = time.subseconds();
}
Pretty ugly
Check out the example on cppreference for std::chrono::zoned_time: https://en.cppreference.com/w/cpp/chrono/zoned_time