c++格式化日期
C++ Formatted Date
这可能是一个非常简单的问题,但是来自PHP世界,在c++中是否有一种简单(而不是全世界)的方式以特定格式输出当前日期?
我希望将当前日期表示为"Y-m-d H: I"(PHP"日期"语法),结果类似于"2013-07-17 18:32"。它总是用16个字符表示(包括前导零)。
我很好包括Boost库,如果有帮助的话。这是香草/linux c++虽然(没有Microsoft头文件)。
非常感谢!
strftime是我能想到的没有boost的最简单的方法。Ref and example: http://en.cppreference.com/w/cpp/chrono/c/strftime
你的意思是:
#include <iostream>
#include <ctime>
using namespace std;
int main( )
{
// current date/time based on current system
time_t now = time(0);
// convert now to string form
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
}
结果:The local date and time is: Sat Jan 8 20:07:41 2011
The UTC date and time is:Sun Jan 9 03:07:41 2011
c++ 11支持std::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';
std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(&tm, "%c %Z") << 'n';
}
传统的C
方法是使用strftime
,它可以用来格式化time_t
(PHP允许您使用当前时间或"从其他地方获得的时间戳"),所以如果您想要"现在",您需要先调用time
。
您可以使用boost日期面来使用给定的格式打印日期:
//example to customize output to be "LongWeekday LongMonthname day, year"
// "%A %b %d, %Y"
date d(2005,Jun,25);
date_facet* facet(new date_facet("%A %B %d, %Y"));
std::cout.imbue(std::locale(std::cout.getloc(), facet));
std::cout << d << std::endl;
// "Saturday June 25, 2005"
或者再次使用boost date time库也是可能的,尽管方式不完全相同。
//Output the parts of the date - Tuesday October 9, 2001
date::ymd_type ymd = d1.year_month_day();
greg_weekday wd = d1.day_of_week();
std::cout << wd.as_long_string() << " "
<< ymd.month.as_long_string() << " "
<< ymd.day << ", " << ymd.year
<< std::endl;
正如其他答案所建议的那样,使用strftime函数对于简单的情况可能更容易,并且从c++开始,即使它最初是一个C函数:)
相关文章:
- 查询SQLite数据库中的日期
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- C++格式化输出问题
- Log4cpp:以UTC/GMT时区打印日期
- 使用C++的日期库读取时间
- 格式化浮点值:返回默认值
- 日期格式为C++
- 如何在 C++20 计时中为日期添加天数?
- 自动格式化程序> >更改为>>
- 如何从C++中的格式化字符串派生整数?
- 使用 C++将时间戳转换为格式化的日期时间
- 如何读取和处理格式化的日期,如 01/11/1998、星期日(10000 个输入)C++
- Poco 日期时间格式化程序 - 使用当前时区打印时间戳
- Qt ISODate格式化的日期/时间,包括时区
- 如何使用 getline 和字符串流来解析格式化的日期和时间输入
- 以格式化的方式打开一个具有日期的文件,并获取该日期进行比较
- c++格式化日期
- 格式化QTableView显示的日期/时间值
- 在c++中自定义时区格式化日期/时间
- QT重新格式化日期时间字符串