C++11 alternative to localtime_r

▼魔方 西西 提交于 2019-11-28 20:08:06

You're not missing anything.

The next C standard (due out probably this year) does have defined in Annex K:

struct tm *localtime_s(const time_t * restrict timer,
                       struct tm * restrict result);

And this new function is thread safe! But don't get too happy. There's two major problems:

  1. localtime_s is an optional extension to C11.

  2. C++11 references C99, not C11. local_time_s is not to be found in C++11, optional or not.

Update

In the 4 years since I answered this question, I have also been frustrated by the poor design of C++ tools in this area. I was motivated to create modern C++ tools to deal with this:

http://howardhinnant.github.io/date/tz.html

#include "tz.h"
#include <iostream>

int
main()
{
    using namespace date;
    auto local_time = make_zoned(current_zone(), std::chrono::system_clock::now());
    std::cout << local_time << '\n';
}

This just output for me:

2015-10-28 14:17:31.980135 EDT

local_time is a pairing of std::chrono::system_clock::time_point and time_zone indicating the local time.

There exists utilities for breaking the std::chrono::system_clock::time_point into human-readable field types, such as year, month, day, hour, minute, second, and subseconds. Here is a presentation focusing on those (non-timezone) pieces:

https://www.youtube.com/watch?v=tzyGjOm8AKo

All of this is of course thread safe (it is modern C++).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!