Source
stdlib/datetime/datetime.cpp
1
// Copyright (c) 2026 BigBrain LLC. MIT-licensed (see LICENSE).2
// Original work; see ACKNOWLEDGMENTS.md for the open-source ideas we build upon.3
#include "datetime.hpp"5
#include <chrono>6
#include <ctime>8
namespace cheatah::datetime {10
namespace {11
std::tm local_tm(double epoch) {12
const std::time_t t = static_cast<std::time_t>(epoch);13
std::tm out{};14
localtime_r(&t, &out);15
return out;16
}17
std::string strf(const std::tm& tm, const char* fmt) {18
char buf[128];19
const std::size_t n = std::strftime(buf, sizeof(buf), fmt, &tm);20
return std::string(buf, n);21
}22
} // namespace24
double timestamp() {25
return std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch())26
.count();27
}28
std::string now() { return strf(local_tm(timestamp()), "%Y-%m-%d %H:%M:%S"); }29
std::string utcnow() {30
const std::time_t t = static_cast<std::time_t>(timestamp());31
std::tm out{};32
gmtime_r(&t, &out);33
return strf(out, "%Y-%m-%dT%H:%M:%SZ");34
}35
std::string today() { return strf(local_tm(timestamp()), "%Y-%m-%d"); }37
std::string format(double epoch, std::string_view fmt) {38
return strf(local_tm(epoch), std::string(fmt).c_str());39
}41
int year(double e) { return local_tm(e).tm_year + 1900; }42
int month(double e) { return local_tm(e).tm_mon + 1; }43
int day(double e) { return local_tm(e).tm_mday; }44
int hour(double e) { return local_tm(e).tm_hour; }45
int minute(double e) { return local_tm(e).tm_min; }46
int second(double e) { return local_tm(e).tm_sec; }47
int weekday(double e) { return (local_tm(e).tm_wday + 6) % 7; } // Sun=0 -> Mon=049
} // namespace cheatah::datetime