【问题标题】:How to show time from a time stamp and show current time when I have no argument?当我没有参数时,如何从时间戳显示时间并显示当前时间?
【发布时间】:2021-01-31 11:06:29
【问题描述】:

我需要创建一个函数,它需要一个时间戳(以毫秒为单位的时间,输入long)并将其转换为可读时间(Y-M-D H:M:S);但是,在那之后,我必须重载函数,这样如果函数没有获取参数,它将返回当前日期。

我知道如何使函数从给定的长参数转换为可读时间,但我不知道如何重载函数。

#include <iostream>
#include <cstdio>
#include <ctime>
#include <string>

using namespace std;

string timeToString(long  timestamp)
{
    const time_t rawtime = (const time_t)timestamp; 

    struct tm * dt;
    char timestr[30];
    char buffer [30];

    dt = localtime(&rawtime);
    strftime(timestr, sizeof(timestr), "%Y-%m-%d %X", dt);
    sprintf(buffer,"%s", timestr);
    string stdBuffer(buffer); 
    return stdBuffer;
}

int main()
{
    cout << timeToString(1538123990) << "\n";
}

【问题讨论】:

  • 您的教师需要了解 std::chrono 库并停止将 C 作为 C++ 进行教学
  • 同意@Casey

标签: c++ strftime ctime


【解决方案1】:

首先(如 cmets 中所述)您应该真正使用现代 C++ 库的 std::chrono 函数进行时间操作。但是,坚持使用您拥有的基本代码,您可以为 timeToString 函数的参数提供一个 default 值;这应该是一个在真正意义上没有意义的值,并且你永远不会实际上通过。我在下面的示例中选择了-1,因为您不太可能使用负时间戳。

如果调用函数带有一个参数,则使用该值;否则,使用给定的默认值调用该函数。然后我们可以调整代码来检查该值,如下所示:

#include <iostream>
#include <ctime>
#include <string>

std::string timeToString(long timestamp = -1)
{
    time_t rawtime;                                // We cannot (now) have this as "const"
    if (timestamp < 0) rawtime = time(nullptr);    // Default parameter:- get current time
    else rawtime = static_cast<time_t>(timestamp); // Otherwise convert the given argument

    struct tm* dt = localtime(&rawtime);
    char timestr[30];
//  char buffer[30]; // Redundant (see below)
    strftime(timestr, sizeof(timestr), "%Y-%m-%d %X", dt);
//  sprintf(buffer, "%s", timestr); // This just makes a copy of the same string!
    return std::string(timestr);
}

int main()
{
    std::cout << timeToString(1538123990) << "\n";
    std::cout << timeToString() << "\n"; // No parameter - function will get "-1" instead!
    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 2012-11-28
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多