std::localtime(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

🌸 NAME 🌸

std::localtime - std::localtime

okay so bestie, this is std::localtime(3) from the C++ Standard Libary β€” yes, that manual-name spelling is a whole choice, and we're keeping it. It's the function that turns epoch time into local calendar time. πŸ’–

✨ Synopsis ✨

Defined in header <ctime>:

std::tm* localtime( const std::time_t* time );

It converts the given time since epoch as a std::time_t value into calendar time, expressed in local time. That's the assignment, no cap. πŸ•°οΈ

πŸŽ€ Parameters πŸŽ€

  • time β€” pointer to a std::time_t object to convert. that's the input, bestie.

🫢 Return value 🫢

On success you get a pointer to a static internal std::tm object; otherwise you get a null pointer. 😭

Heads up: that structure may be shared between std::gmtime, std::localtime, and std::ctime, and it may be overwritten on each invocation. so don't get too attached to the pointer, okay? πŸ’…

πŸ’… Notes πŸ’…

  • This function may not be thread-safe.
  • POSIX requires that this function sets errno to EOVERFLOW if it fails because the argument is too large.
  • POSIX specifies that the timezone information is determined by this function as if by calling tzset, which reads the environment variable TZ.
⚠️ thread-safety is giving "shared static structure, be careful," bestie. The notes are not decorative.

🌈 Example 🌈

// Run this code

#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>

int main()
{
    setenv("TZ", "/usr/share/zoneinfo/America/Los_Angeles", 1); // POSIX-specific

    std::tm tm{}; // Zero initialise
    tm.tm_year = 2020 - 1900; // 2020
    tm.tm_mon = 2 - 1; // February
    tm.tm_mday = 15; // 15th
    tm.tm_hour = 10;
    tm.tm_min = 15;
    tm.tm_isdst = 0; // Not daylight saving
    std::time_t t = std::mktime(&tm);

    std::cout << "UTC:   " << std::put_time(std::gmtime(&t), "%c %Z") << '\n';
    std::cout << "local: " << std::put_time(std::localtime(&t), "%c %Z") << '\n';
}

Possible output:

UTC:   Sat Feb 15 18:15:00 2020 GMT
local: Sat Feb 15 10:15:00 2020 PST

πŸ‘€ See also πŸ‘€

  • gmtime β€” converts time since epoch to calendar time expressed as Universal Coordinated Time (function)
  • localtime
  • localtime_r β€” converts time since epoch to calendar time expressed as local time (function)
  • localtime_s β€” (function) (C23) (C11)
  • C documentation for localtime

source/version + date sign-off: http://cppreference.com, 2024.06.10, page std::localtime(3) β€” bye bestie, go convert some epochs πŸ’…βœ¨

πŸ“¦ where this page comes from