c++格式化日期

C++ Formatted Date

本文关键字:日期 格式化 c++      更新时间:2023-10-16

这可能是一个非常简单的问题,但是来自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函数:)