std::gmtime(3)

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

🌍 std::gmtime(3) β€” C++ Standard Library, bestie edition ✨

okay so we're doing std::gmtime today, from the <ctime> header, and honestly? she's iconic. πŸ•βœ¨


πŸ’– NAME πŸ’–

std::gmtime β€” literally std::gmtime, that's it, that's the name πŸŽ€


🌸 SYNOPSIS 🌸

Defined in header <ctime>:

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

So what does it do? It converts a given time since epoch (as a std::time_t value) into calendar time, expressed in Coordinated Universal Time (UTC). 🌍 No cap, that's the whole vibe.


πŸ¦‹ PARAMETERS πŸ¦‹

  • time β€” a pointer to a time_t object to convert 🫢

That's it. One little pointer. She's low maintenance, we love that for her πŸ’…


πŸ‘‘ RETURN VALUE πŸ‘‘

You get back a pointer to a static internal std::tm object on success, or a null pointer otherwise. πŸŽ€

⚠️ okay listen bestie, this part matters: that structure may be shared between std::gmtime, std::localtime, and std::ctime, and may be overwritten on each invocation. So like… don't get too attached to it? It's giving "main character shared with three other functions" energy. 😭 Copy it if you need it to survive.

πŸ’œ NOTES πŸ’œ

  • This function may not be thread-safe. fr fr, be careful out there 🧚
  • POSIX requires that this function sets errno to EOVERFLOW if it fails because the argument is too large. πŸ“βœ¨

πŸ”₯ EXAMPLE πŸ”₯

// Run this code

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

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

    std::tm tm{}; // get_time does not set all fields hence {}
    tm.tm_year = 2020 - 1900; // 2020
    tm.tm_mon = 7 - 1; // July
    tm.tm_mday = 15; // 15th
    tm.tm_hour = 10;
    tm.tm_min = 15;
    tm.tm_isdst = 1; // Daylight saving in London
    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:   Wed Jul 15 09:15:00 2020 GMT
local: Wed Jul 15 10:15:00 2020 BST

see how UTC and local are one hour apart? that's the whole point, bestie β€” same moment, two timezones, and gmtime is the UTC one πŸ•β†’πŸ•‘πŸ’«


πŸ“ SEE ALSO πŸ“

  • localtime β€” converts time since epoch to calendar time expressed as local time (function) 🏠
  • C documentation for gmtime πŸ“š

k that's the whole page, mwah πŸ’‹ β€” this lil gem comes from http://cppreference.com, dated 2024.06.10 (and it's literally titled std::gmtime(3) in case you forgot where you were πŸ’–). stay hydrated, set your errno, and go convert some timestamps πŸŽ€βœ¨πŸ¦‹

πŸ“¦ where this page comes from