4

这可能是一个非常简单的问题,但来自 PHP 世界,是否有一种简单(而不是世界范围内)的方法可以在 C++ 中以特定格式输出当前日期?

我希望将当前日期表示为“Ymd H:i”(PHP“日期”语法),结果类似于“2013-07-17 18:32”。它总是用 16 个字符(包括前导零)表示。

如果有帮助,我可以包括 Boost 库。这是 vanilla/linux C++(没有 Microsoft 头文件)。

非常感谢!

4

5 回答 5

4

strftime 是我能想到的最简单的,没有提升。参考和示例:http: //en.cppreference.com/w/cpp/chrono/c/strftime

于 2013-06-17T15:41:52.963 回答
3

你的意思是这样的:

#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
于 2013-06-17T15:41:48.707 回答
2

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';
}
于 2016-12-29T21:39:33.110 回答
1

传统的C方法是使用strftime,它可以用来格式化a time_t(PHP允许你使用当前时间或“从其他地方得到的时间戳”),所以如果你想要“现在”,你需要先调用time

于 2013-06-17T15:42:48.833 回答
0

您可以使用 boost date facets使用给定格式打印日期:

//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"

或者再次使用提升日期时间库是可能的,尽管方式不完全相同。

  //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 函数:)

于 2013-06-17T15:42:57.147 回答