概述
c++格式化时间
方法一(作者使用的方法)、strftime()函数
#include <ctime>
#include <string>
#include <sstream>
std::string stime;
std::stringstream strtime;
std::time_t currenttime = std::time(0);
char tAll[255];
std::strftime(tAll, sizeof(tAll), "%Y-%m-%d-%H-%M-%S", std::localtime(¤ttime));
strtime << tAll;
stime = strtime.str();
注意:对于localtime()函数windows平台会报错。
'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
需要使用微软提供的 localtime_s 或者 添加消除警告的宏。
这里使用vs2015,在IDE里添加里消除警告的宏 _CRT_SECURE_NO_DEPRECATE
项目->属性->配置属性->C/C++ -> 预处理器 -> 预处理器定义
Project->Properties->Configration Properties->C/C++->Preprocessor->Preprocessor Definitions
参照:
http://stackoverflow.com/questions/10289017/how-to-format-date-and-time-string-in-c
http://stackoverflow.com/questions/16357999/current-date-and-time-as-string
http://blog.csdn.net/shellching/article/details/8114266
http://www.cnblogs.com/gb2013/archive/2013/03/05/SecurityEnhancementsInTheCRT.html
http://stackoverflow.com/questions/14386923/localtime-vs-localtime-s-and-appropriate-input-arguments
方法二、c++11 的put_time()函数
来源:http://en.cppreference.com/w/cpp/io/manip/put_time
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);
std::cout.imbue(std::locale("ru_RU.utf8"));
std::cout << "ru_RU: " << std::put_time(&tm, "%c %Z") << 'n'; // %Y-%m-%d %H:%M:%S
std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(&tm, "%c %Z") << 'n';
}
方法三、time_put()函数
来源: https://www.safaribooksonline.com/library/view/c-cookbook/0596007612/ch05s03.html
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <string>
#include <stdexcept>
#include <iterator>
#include <sstream>
using namespace std;
ostream& formatDateTime(ostream& out, const tm& t, const char* fmt) {
const time_put<char>& dateWriter = use_facet<time_put<char> >(out.getloc());
int n = strlen(fmt);
if (dateWriter.put(out, out, ' ', &t, fmt, fmt + n).failed()) {
throw runtime_error("failure to format date time");
}
return out;
}
string dateTimeToString(const tm& t, const char* format) {
stringstream s;
formatDateTime(s, t, format);
return s.str();
}
tm now() {
time_t now = time(0);
return *localtime(&now);
}
int main()
{
try {
string s = dateTimeToString(now(), "%A %B, %d %Y %I:%M%p");
cout << s << endl;
s = dateTimeToString(now(), "%Y-%m-%d %H:%M:%S");
cout << s << endl;
}
catch(...) {
cerr << "failed to format date time" << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
最后
以上就是精明啤酒为你收集整理的C++格式化时间的全部内容,希望文章能够帮你解决C++格式化时间所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复