C 将NTP服务器返回的时间转换为字符串
c++ convert time returned by NTP server to string
我是C 的新手,想从NTP服务器转换为人类可读日期时间值。
void printTime() {
/*
Human time (GMT): Friday, May 17, 2019 8:44:16 AM
Human time (your time zone): Friday, May 17, 2019 10:44:16 AM GMT+02:00
*/
unsigned long e = 1558082656;
time_t epoch = e;
struct tm *timeinfo_e;
char buf[80];
time(&epoch);
timeinfo_e = gmtime(&epoch);
std::cout << "epoch: " << asctime(timeinfo_e) << std::endl;
strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", timeinfo_e);
printf("%sn", buf);
}
,但它显示了当前时间,而不是该时期值的时间。有什么问题?
谢谢!
time(&epoch);
这将当前时间存储到epoch
中,覆盖您先前分配的值。如果您取出该内容,您的程序将显示您分配给epoch
的UNIX时间。
但是,C 具有其自己的DateTime库,并且计划得到极大改进的C 20,它应该能够完全避免C API。截至今天,您已经可以看到我称之为理解代码的改进:
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
namespace chr = std::chrono;
void printTime() {
using Clock = chr::system_clock;
unsigned long e = 1558082656;
chr::time_point<Clock> time(chr::seconds{e});
auto c_time = Clock::to_time_t(time); // Gone if using C++20's to_stream function
std::cout << std::put_time(std::gmtime(&c_time), "%c %Z"); // localtime for the user's timezone
}
,如果您觉得当前有一些回旋处要转到time_point
并返回,尽管自时钟时代以来明确指示了几秒钟,则put_time
仍然可以用作打印C时间的更方便的方法。
相关文章:
- 时间转换为 24 小时格式 cpp
- C++:将Unix时间转换为非本地时区
- 将带有时区的纪元时间转换为Excel格式的时间?
- 如何将纪元时间转换为time_point
- 如何将标准::时间::d转换为双倍(秒)?
- 在 c++ 中将 ISO 日期时间转换为本地日期时间并提取时间
- C 将NTP服务器返回的时间转换为字符串
- 将时间转换为小时、分钟和秒
- 将文本日期和时间转换为 ATL::CTime
- C Winapi:如何将当前时间转换为字符串
- 12小时到24小时的时间转换
- 如何将Milli秒的时间转换为C 中的filtime
- C 将日期时间转换为时间戳
- 将 NTP 时间转换为日期时偏移 1 天
- 时间转换的建议代码
- 将时间转换为分钟和秒
- 如何将存储在字符串变量中的时间转换为时间格式
- 将ISO时间转换为std::chrono::time_point
- 时间转换程序
- 如何将时间转换为纪元时间