cheatah
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>
8namespace cheatah::datetime {
10namespace {
11std::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;
17std::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);
22} // namespace
24double timestamp() {
25 return std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch())
26 .count();
28std::string now() { return strf(local_tm(timestamp()), "%Y-%m-%d %H:%M:%S"); }
29std::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");
35std::string today() { return strf(local_tm(timestamp()), "%Y-%m-%d"); }
37std::string format(double epoch, std::string_view fmt) {
38 return strf(local_tm(epoch), std::string(fmt).c_str());
41int year(double e) { return local_tm(e).tm_year + 1900; }
42int month(double e) { return local_tm(e).tm_mon + 1; }
43int day(double e) { return local_tm(e).tm_mday; }
44int hour(double e) { return local_tm(e).tm_hour; }
45int minute(double e) { return local_tm(e).tm_min; }
46int second(double e) { return local_tm(e).tm_sec; }
47int weekday(double e) { return (local_tm(e).tm_wday + 6) % 7; } // Sun=0 -> Mon=0
49} // namespace cheatah::datetime