c++ - 如何在 C++ 中使用 unix 时间格式化 time_t 中的时间/日期字符串
问题描述
我有一个time_t值,我需要从中提取年、月、dayOfMonth、hourOfDay、分钟和秒的值(作为整数)。如果可能的话,我想尽量减少对库的依赖,但如果有一个库函数,你可以合理地确定它总是可用的,那就没问题了。time_t 值应该已经针对时区进行了调整,所以不用担心。
由于在一个相当大的公司项目中工作并使用远程服务器构建应用程序,我实际上不知道我们使用的是哪个版本的 C++,但它很可能是 C++11(可能是 C++98,但我对此表示怀疑) ,而且几乎可以肯定不是 C++17)。
解决方案
If you have a time_t
(which is from <time.h>
), you don't need any additional library. You can just use the tm
struct and localtime
function that are also in <time.h>
:
#include <iostream>
#include <time.h>
int main() {
time_t t;
t = time(NULL); // or some other value
tm *timeNow = localtime(&t);
std::cout << "Year: " << timeNow->tm_year+1900 << std::endl;
std::cout << "Month: " << timeNow->tm_mon << std::endl;
std::cout << "Day: " << timeNow->tm_mday << std::endl;
std::cout << "Hour: " << timeNow->tm_hour << std::endl;
std::cout << "Minute: " << timeNow->tm_min << std::endl;
std::cout << "Second: " << timeNow->tm_sec << std::endl;
}
推荐阅读
- python - 如何使 Python 应用程序的某些操作可以通过网络访问?
- reactjs - 使用 socketio 将动作发送到不同的反应组件中
- java - Java Graphics drawImage 有时会很慢,有时会在 JPanel 上暂停
- javascript - 下一个 JS 图像优化
- shopify - Shopify 订单状态不清楚
- firebase - Firestore 安全规则,如何检查声明是否存在并且是字符串
- css - Blazor Webassembly:CSS:未应用主机变量
- c# - 对象的位置和旋转未保存/加载(Unity 引擎)
- ruby-on-rails-5 - Active Storage not resizing images
- javascript - Fetched data duplicates itself after sorting