【C++每日一练】4.获取当前系统时间、系统时间戳
【摘要】
需求:获取当前系统时间、系统时间戳
#include <iostream>
#include <chrono>
#include <cstdio>
usin...
需求:获取当前系统时间、系统时间戳
#include <iostream>
#include <chrono>
#include <cstdio>
using namespace std;
std::time_t getTimeStamp()
{
std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
std::time_t timestamp = tmp.count();
return timestamp;
}
std::tm *gettm(long long timestamp)
{
auto milli = timestamp + (long long)8 * 60 * 60 * 1000; //此处转化为东八区北京时间,如果是其它时区需要按需求修改
auto mTime = std::chrono::milliseconds(milli);
auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(mTime);
auto tt = std::chrono::system_clock::to_time_t(tp);
std::tm *now = std::gmtime(&tt);
return now;
}
int main()
{
char time_str[4][16];
auto t = getTimeStamp();
std::cout << "Millisecond timestamp is: " << t << std::endl;
auto time_ptr = gettm(t);
sprintf(time_str[0], "%02d", time_ptr->tm_mon + 1); //月份要加1
sprintf(time_str[1], "%02d", time_ptr->tm_mday);//天
sprintf(time_str[2], "%02d", time_ptr->tm_hour);//时
sprintf(time_str[3], "%02d", time_ptr->tm_min);// 分
for(int i = 0; i < 4; i++)
{
std::cout << "time_str[" << i << "] is: " << time_str[i] << std::endl;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
文章来源: yujiang.blog.csdn.net,作者:鱼酱2333,版权归原作者所有,如需转载,请联系作者。
原文链接:yujiang.blog.csdn.net/article/details/122018583
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)