C++: 如何通过 time 和 localtime 获取实际时间?

发布于 2024-12-13 19:22:07 字数 1494 浏览 8 评论 0原文

我正在寻找一种在 C++ 中以 HH::MM::SS 方式节省时间的方法。我在这里看到它们有很多解决方案,经过一番研究后,我选择了 timelocaltime。然而,似乎 localtime 函数有点棘手,因为它 说:

对 localtime 和 gmtime 的所有调用都使用相同的静态结构,因此 每次调用都会覆盖前一个调用的结果。

这导致的问题如下面的代码片段所示:

#include <ctime>
#include <iostream>
using namespace std;

int main() {
time_t t1 = time(0);   // get time now
struct tm * now = localtime( & t1 );

std::cout << t1 << std::endl;
sleep(2);
time_t t2 = time(0);   // get time now
struct tm * now2 = localtime( & t2 );
std::cout << t2 << std::endl;

cout << (now->tm_year + 1900) << '-'
     << (now->tm_mon + 1) << '-'
     <<  now->tm_mday << ", "
     << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec
     << endl;

cout << (now2->tm_year + 1900) << '-'
     << (now2->tm_mon + 1) << '-'
     <<  now2->tm_mday << ", "
     << now2->tm_hour << ":" << now2->tm_min << ":" << now2->tm_sec
     << endl;
}

典型的输出是:

1320655946
1320655948
2011-11-7, 9:52:28
2011-11-7, 9:52:28

正如您所看到的,time_t 时间戳是正确的,但本地时间却把一切搞乱了。

我的问题是:如何将 time_t 类型的时间戳转换为人类可读的时间?

I'm looking for a way to save the time in a HH::MM::SS fashion in C++. I saw here that they are many solutions and after a little research I opted for time and localtime. However, it seems like the localtime function is a little tricky, since it says:

All calls to localtime and gmtime use the same static structure, so
each call overwrites the results of the previous call.

The problem that this causes is shown in the next snippet of code:

#include <ctime>
#include <iostream>
using namespace std;

int main() {
time_t t1 = time(0);   // get time now
struct tm * now = localtime( & t1 );

std::cout << t1 << std::endl;
sleep(2);
time_t t2 = time(0);   // get time now
struct tm * now2 = localtime( & t2 );
std::cout << t2 << std::endl;

cout << (now->tm_year + 1900) << '-'
     << (now->tm_mon + 1) << '-'
     <<  now->tm_mday << ", "
     << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec
     << endl;

cout << (now2->tm_year + 1900) << '-'
     << (now2->tm_mon + 1) << '-'
     <<  now2->tm_mday << ", "
     << now2->tm_hour << ":" << now2->tm_min << ":" << now2->tm_sec
     << endl;
}

A typical output for this is:

1320655946
1320655948
2011-11-7, 9:52:28
2011-11-7, 9:52:28

So as you can see, the time_t timestamps are correct, but the localtime messes everything up.

My question is: how do I convert a timestamp ot type time_t into a human-readable time?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

惯饮孤独 2024-12-20 19:22:07

如果您担心 localtimegmtime 中的重入问题,可以使用 localtime_rgmtime_r 来处理多个调用。

当需要根据自己的喜好格式化时间时,请检查函数 strftime

If you are worried about reentrancy in localtime and gmtime, there is localtime_r and gmtime_r which can handle multiple calls.

When it comes to formatting the time to your liking, check the function strftime.

所有深爱都是秘密 2024-12-20 19:22:07

localtime() 调用将结果存储在内部缓冲区中。

每次调用它时都会覆盖缓冲区。
另一种解决方案是制作缓冲区的副本。

time_t      t1  = time(0);           // get time now
struct tm* now  = localtime( & t1 ); // convert to local time
struct tm  copy = *now;              // make a local copy.
 //     ^^^ notice no star.

但请注意:您应该转换为当地时间的唯一时间是显示该值时。在所有其他时间,您应该将时间保留为 UTC(用于存储和操作)。由于您只是转换对象以进行显示转换,然后立即打印,这样就不会出错。

the localtime() call stores the results in an internal buffer.

Every time you call it you overwrite the buffer.
An alternative solution would be to make a copy of the buffer.

time_t      t1  = time(0);           // get time now
struct tm* now  = localtime( & t1 ); // convert to local time
struct tm  copy = *now;              // make a local copy.
 //     ^^^ notice no star.

But note: The only time you should be converting to local time is when you display the value. At all other times you should just keep the time as UTC (for storage and manipulation). Since you are only converting the objects for display convert then print immediately and then things will not go wrong.

初见终念 2024-12-20 19:22:07

localtime 拥有最好被视为遗留接口的东西。不可能是
例如,用于多线程代码。在多线程中
环境下,可以在 Posix 下使用 localtime_rlocaltime_s
在Windows下。否则,您所要做的就是保存结果:

tm then = *localtime( &t1 );
//  ...
tm now = *localtime( &t2 );

但是,仅调用 localtime
可能更惯用
在格式化输出之前,例如:

std::string
timestampToString( time_t timeAndDate )
{
    char results[100];
    if ( strftime( results, sizeof( results ), "%Y-%m-%d, %H:%M:%S", 
                localtime( &timeAndDate) ) == 0 ) {
        assert( 0 );
    }
    return results;
}

然后写入:(

std::cout << formatTime( t1 ) << std::endl;

您还可以创建一个更通用的格式化函数,该函数需要
格式作为参数。)

localtime has what is best considered a legacy interface. It can't be
used in multithreaded code, for example. In a multithreaded
environment, you can use localtime_r under Posix or localtime_s
under Windows. Otherwise, all you have to do is save the results:

tm then = *localtime( &t1 );
//  ...
tm now = *localtime( &t2 );

It would probably be more idiomatic, however, to only call localtime
immediately before formatting the output, e.g.:

std::string
timestampToString( time_t timeAndDate )
{
    char results[100];
    if ( strftime( results, sizeof( results ), "%Y-%m-%d, %H:%M:%S", 
                localtime( &timeAndDate) ) == 0 ) {
        assert( 0 );
    }
    return results;
}

and then writing:

std::cout << formatTime( t1 ) << std::endl;

(You could also create a more generic formatting function, which took
the format as an argument.)

提笔书几行 2024-12-20 19:22:07

您可以使用以下代码运行连续时钟。效果很好。

#include<iostream> 
#include <Windows.h> 
#include<ctime> 
using namespace std;

void main() {
  while(true) {
    system("cls"); //to clear screen
    time_t tim;
    time(&tim); 
    cout << ctime(&tim); 
    Sleep(1);
  }
}

You can run continuous clock using following code. It works nicely.

#include<iostream> 
#include <Windows.h> 
#include<ctime> 
using namespace std;

void main() {
  while(true) {
    system("cls"); //to clear screen
    time_t tim;
    time(&tim); 
    cout << ctime(&tim); 
    Sleep(1);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文