windows timestamp (C++)
windows timestamp (C++)
我创建了windows时间戳()函数,但我通过PHP microtime()函数检查了错误的数字:
- C++=1409802313
- PHP=11410655505
在这个闲置的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_t epochtime = time(NULL);
可变历元时间应包含自1970年初以来的秒数。
您的代码没有考虑闰年,这可能会使您的计算与PHP有所不同。
错误在这里:
time += (year - 1970) * 31536000;
31536000
是365天内的秒数。但自1970年以来,共有11个闰日,这些年有366天。您需要为每个闰日添加86400
。
你的两个结果相差853192。这还不到10天,所以我不确定第11个闰日发生了什么。这也比10天少了3个小时(+8秒,我想这是你两次测试之间的时间);这是因为Unix时间戳是基于GMT,而不是本地时间。