c++ - 如何将时间转换为整数

标签 c++ time int

我有以下代码:

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

const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%X", &tstruct);

    return buf;
}

int main() {   
    std::cout << "Current Time is: " << currentDateTime() << std::endl;
    return 0;
}

我编译这个,我得到:当前时间是:18:30:11

我想知道如何将其转换为整数,使其显示为 18.5 或类似的东西。我想这样做是因为我想创建一个时间表。
示例:如果是 10:30,我希望程序能够告诉我我有什么科目(学校)。 像这样:

if(time == 10.5)
    std::cout<<(subject);

关于如何做到这一点有什么建议吗?我是 c++ 的新手,我不确定我是否以完全错误的方式处理这个问题。还有另一种方法吗? 提前致谢。

最佳答案

我想您的意思是将时间转换为 float 。在您的 currentDateTime 函数中,您已经使用了 struct tm。基于此,您可以通过以下方式获得 float 小时值:

time_t now = time(0);
struct tm tstruct = *localtime(&now);

float f = tstruct.tm_hour + tstruct.tm_min / 60.0 + tstruct.tm_sec / 3600.0;
cout << f << endl; // prints 10.1025 at 10:06:09

关于c++ - 如何将时间转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25544160/

相关文章:

c++ - Qt 小部件在 Windows 中不服从拖放

python - 脚本 B 减慢了脚本 A

Java writer 输出中的第一个字符 (int) 错误

Python String to Int——非常简单但棘手

Java - 从字节转换为int(不是ascii值)

c++ - 关于先序树遍历

c++ - C++ 或任何其他语言的可选结构类型可能性?

c++ - GCC 内联 C++ 函数是否没有 'inline' 关键字?

mysql - 比较触发器 MYSQL 中的日期

php - 在 php/mysql 中跟踪时间冲突的正确算法是什么?