gpt4 book ai didi

c++ - Windows时间戳(C++)

转载 作者:行者123 更新时间:2023-12-02 10:25:49 25 4
gpt4 key购买 nike

我创建了Windows timestamp()函数,并通过PHP microtime()函数检查了错误的数字:

  • C++ = 1409802313
  • PHP = 1410655505

  • 在这个休闲的C++编写的代码中:
    #include <windows.h>
    #include <iostream> // <--- Console I/O
    #include <cstdlib> // <--- Command Line
    #include <sstream>

    using namespace std;

    void print(string value){cout << value;}

    string parseStr(int value)
    {
    ostringstream stream;
    stream<<value<<flush;

    return stream.str();
    }


    // ============================================================
    // TIMESTAMP
    // ============================================================
    string timestamp()
    {
    SYSTEMTIME system_time;
    GetLocalTime(&system_time);

    int year = system_time.wYear;
    int month = system_time.wMonth;
    int day = system_time.wDay;
    int hour = system_time.wHour;
    int minute = system_time.wMinute;
    int second = system_time.wSecond;
    int milliseconds = system_time.wMilliseconds;

    int day_of_year = 0;
    if (month > 1){day_of_year += 31;} // Sausis
    if (month > 2){day_of_year += 28;} // Vasaris
    if (month > 3){day_of_year += 31;} // Kovas
    if (month > 4){day_of_year += 30;} // Balandis
    if (month > 5){day_of_year += 31;} // Geguze
    if (month > 6){day_of_year += 30;} // Birzelis
    if (month > 7){day_of_year += 31;} // Liepa
    if (month > 8){day_of_year += 31;} // Rugpjutis
    if (month > 9){day_of_year += 30;} // Rugsejis
    if (month > 10){day_of_year += 31;} // Spalis
    if (month > 11){day_of_year += 30;} // Lapkritis
    if (month > 12){day_of_year += 31;} // Gruodis
    day_of_year += day;

    int time = 0;
    time += (year - 1970) * 31536000;
    time += day_of_year * 86400;
    time += hour * 3600;
    time += minute * 60;
    time += second;

    string time_string;
    time_string = parseStr(time);

    return time_string;
    }
    // ============================================================

    int main()
    {
    while(true)
    {
    system("cls");

    string time = timestamp();
    print(time);

    Sleep(100);
    }

    return 0;
    }

    我会计算错误还是整数类型错误? :(

    最佳答案

    错误在这里:

    time += (year - 1970) * 31536000;
    31536000是365天的秒数。但是自1970年以来已经有11个leap日,那年有366天。您需要为每个the日添加 86400

    您的两个结果之间的差是853192。这还不到10天,所以我不确定第11个leap日发生了什么。还不到10天3个小时(+ 8秒,我猜这是您两次测试之间的时间);这是因为Unix时间戳基于GMT,而不是本地时间。

    关于c++ - Windows时间戳(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829208/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com