如何在Linux中使用C语言将日期和时间字符串精确到毫秒?
我希望能够将具有毫秒分辨率的本地时间和日期放入字符串中,如下所示:
YYYY-MM-DD hh:mm:ss.sss 这似乎是一件简单的事情,但我还没有找到一个简单的答案来解决这个问题.我用C语言编写并且可以访问11个编译器,但是如果它更清洁则可以使用C解决方案.我在这里发现了一个解决方案Get both date and time in milliseconds的帖子,但是使用标准库肯定不会那么困难.我可能会继续推进这种类型的解决方案,但希望通过在SO上提出问题来增加知识库. 我知道这会起作用,但似乎又不必要地困难: #include <sys/time.h> #include <stdio.h> int main(void) { string sTimestamp; char acTimestamp[256]; struct timeval tv; struct tm *tm; gettimeofday(&tv,NULL); tm = localtime(&tv.tv_sec); sprintf(acTimestamp,"%04d-%02d-%02d %02d:%02d:%02d.%03dn",tm->tm_year + 1900,tm->tm_mon + 1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,(int) (tv.tv_usec / 1000) ); sTimestamp = acTimestamp; cout << sTimestamp << endl; return 0; } 尝试用旧C语言查看put和for for C和strftime.两者都只允许我达到我能说的最佳分辨率.你可以看到我到目前为止得到的两种方法.我想把它变成一个字符串 auto t = std::time(nullptr); auto tm = *std::localtime(&t); std::cout << std::put_time(&tm,"%Y-%m-%d %H:%M:%S") << std::endl; time_t rawtime; struct tm * timeinfo; char buffer[80]; time (&rawtime); timeinfo = localtime(&rawtime); strftime(buffer,sizeof(buffer),"%Y-%m-%d %I:%M:%S",timeinfo); std::string str(buffer); std::cout << str; 我唯一能弄清楚的是使用gettimeofday并除去最后一秒之外的所有数据并将其附加到时间戳,仍然希望有一个更清洁的方法. 有人找到一个更好的解决方案? 解决方法
我建议查看Howard Hinnant的
date library.其中一个
examples given in the wiki显示了如何获得当前的本地时间,达到std :: chrono :: system_clock实现的给定精度(Linux上的纳秒,来自内存?):
编辑:正如霍华德在评论中指出的那样,你可以使用date :: floor()来获得所需的精度.因此,要根据问题中的请求生成字符串,您可以执行以下操作: #include "tz.h" #include <iostream> #include <string> #include <sstream> std::string current_time() { const auto now_ms = date::floor<std::chrono::milliseconds>(std::chrono::system_clock::now()); std::stringstream ss; ss << date::make_zoned(date::current_zone(),now_ms); return ss.str(); } int main() { std::cout << current_time() << 'n'; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |