在 C++ 中将秒转换为 UNIX 时间戳
这是我的代码,应该在传递时间戳后显示两个完整日期:
#include <iostream>
#include <fstream>
#include <time.h>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
time_t startTime_t = (time_t) argv[1];
time_t endTime_t = (time_t) argv[2];
cout << argv[1] << endl << argv[2] << endl;
cout << startTime_t << endl << endTime_t << endl;
string startTime = asctime(localtime(&startTime_t));
string endTime = asctime(localtime(&endTime_t));
cout << startTime << endl << endTime << endl;
return 0;
}
我在从秒到 time_t 的转换上做了一些错误,正如您可以通过此输出看到的:
$ ./a 1325783860 1325791065
1325783860
1325791065
1629762852
1629763900
Mon Aug 23 19:54:12 2021
Mon Aug 23 20:11:40 2021
供参考:
$ date -d @1325783860
Thu Jan 5 12:17:40 EST 2012
Here is my code that should display two full dates after being passed timestamps:
#include <iostream>
#include <fstream>
#include <time.h>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
time_t startTime_t = (time_t) argv[1];
time_t endTime_t = (time_t) argv[2];
cout << argv[1] << endl << argv[2] << endl;
cout << startTime_t << endl << endTime_t << endl;
string startTime = asctime(localtime(&startTime_t));
string endTime = asctime(localtime(&endTime_t));
cout << startTime << endl << endTime << endl;
return 0;
}
I'm doing something wrong with the conversion from seconds to time_t, as you can see by this output:
$ ./a 1325783860 1325791065
1325783860
1325791065
1629762852
1629763900
Mon Aug 23 19:54:12 2021
Mon Aug 23 20:11:40 2021
For reference:
$ date -d @1325783860
Thu Jan 5 12:17:40 EST 2012
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能只将字符串指针转换为 time_t。使用 atol() 从字符串中获取 long,然后将其转换为 time_t。
您返回的值是解释为时间的指针算术值,或者本质上是随机的。
You can't just cast a string pointer to a time_t. Use atol() to get a long from your string, and then cast that to a time_t.
The values you are getting back are the pointer arithmetic value interpreted as a time, or essentially random.