C++:如何获得时间和本地时间的实际时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8034469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:53:54  来源:igfitidea点击:

C++: how to get the actual time with time and localtime?

c++timelocaltime

提问by seb

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 timeand localtime. However, it seems like the localtimefunction is a little tricky, since it says:

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

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

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

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_ttimestamps are correct, but the localtime messes everything up.

如您所见,time_t时间戳是正确的,但本地时间将一切搞砸了。

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

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

回答by Some programmer dude

If you are worried about reentrancy in localtimeand gmtime, there is localtime_rand gmtime_rwhich can handle multiple calls.

如果您担心localtimeand 的可重入性gmtime,有localtime_randgmtime_r可以处理多个调用。

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

在根据自己的喜好格式化时间时,请检查功能strftime

回答by Martin York

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

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

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.

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

回答by James Kanze

localtimehas 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_runder Posix or localtime_sunder Windows. Otherwise, all you have to do is save the results:

localtime有什么最好被认为是遗留接口。例如,它不能用于多线程代码。在多线程环境下,可以localtime_r在 Posixlocaltime_s下使用,也可以在 Windows 下使用。否则,您所要做的就是保存结果:

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.:

然而,仅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;
}

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.)

(您还可以创建一个更通用的格式化函数,它将格式作为参数。)

回答by Snehal

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);
  }
}