c++ - 有没有办法在结构中存储日期和时间? C++

标签 c++ date time struct

我需要将当前日期和时间存储在字符串上,以将其存储在结构中。我什至不知道这是否可能,但我需要这样做。我将尝试进一步解释它:

我有这个结构:

struct Apartment{
int number;
string owner;
string condition;
}ap

此代码添加相同结构的新对象:

cout << "Enter the apartment number: " << endl;
cin >> ap.number;
cout << "Enter the name of the owner: " << endl;
cin >> ap.owner;
cout << "Enter the condition: " << endl;
cin >> ap.condition;

我需要一个日期和时间变量。我需要它来保存对象创建的时间和日期。我不知道是否可以用绳子或任何其他东西来做到这一点。我也需要它可以打印。如果您能帮助我,我将非常感激。

最佳答案

您可以使用std::time_t , std::time()std::ctime()像这样:

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

struct Apartment
{
    int number;
    std::string owner;
    std::string condition;
    std::time_t when;
};

int main()
{
    Apartment ap;

    std::cout << "Enter the apartment number: " << std::endl;
    std::cin >> ap.number;

    std::cout << "Enter the name of the owner: " << std::endl;
    std::cin >> ap.owner;

    std::cout << "Enter the condition: " << std::endl;
    std::cin >> ap.condition;

    ap.when = std::time(0);// set the time to now

    std::cout << "Record created on: " << std::ctime(&ap.when) << std::endl;
}

关于c++ - 有没有办法在结构中存储日期和时间? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061252/

相关文章:

php - 跨 PHP、MySQL 等管理日期的最佳方式是什么?

java - 在 Java8 Date API 中将持续时间转换为年?

mysql - 如何阻止 '0000-00-00 00:00:00' 日期值进入我的 MySQL 表?

javascript - 使用 Javascript 和 Apps 脚本转换 DateTime 字符串

java - 确定时间戳是否是精确的小时

c++ - 如何将libcurl构建为静态库并在项目中使用?

c++ - 在 C++11 中没有用于调用 'evaluate_net_weight' 的匹配函数

c++ - 写入文件的问题

c++ - 在源文件中定义数组并在其他源文件中使用它

linux - 在指定时间运行 bash linux 命令