在c++中是否有跨平台的方法来获取当前的日期和时间?


当前回答

#include <Windows.h>

void main()
{
     //Following is a structure to store date / time

SYSTEMTIME SystemTime, LocalTime;

    //To get the local time

int loctime = GetLocalTime(&LocalTime);

    //To get the system time

int systime = GetSystemTime(&SystemTime)

}

其他回答

#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );

  return 0;
} 

(给谷歌人)

还有Boost::date_time:

#include <boost/date_time/posix_time/posix_time.hpp>

boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
#include <iostream>
#include <chrono>
#include <string>
#pragma warning(disable: 4996)
// Ver: C++ 17 
// IDE: Visual Studio
int main() {
    using namespace std; 
    using namespace chrono;
    time_point tp = system_clock::now();
    time_t tt = system_clock::to_time_t(tp);
    cout << "Current time: " << ctime(&tt) << endl;
    return 0;
}

下面是不弃用的现代c++解决方案,用于将时间戳作为std::string用于例如文件名:

std::string get_file_timestamp()
{
    const auto now = std::chrono::system_clock::now();
    const auto in_time_t = std::chrono::system_clock::to_time_t(now);

    std::stringstream output_stream;

    struct tm time_info;
    const auto errno_value = localtime_s(&time_info, &in_time_t);
    if(errno_value != 0)
    {
        throw std::runtime_error("localtime_s() failed: " + std::to_string(errno_value));
    }

    output_stream << std::put_time(&time_info, "%Y-%m-%d.%H_%M_%S");
    return output_stream.str();
}

是的,你可以这样做的格式规则指定的当前填充区域:

#include <iostream>
#include <iterator>
#include <string>

class timefmt
{
public:
    timefmt(std::string fmt)
        : format(fmt) { }

    friend std::ostream& operator <<(std::ostream &, timefmt const &);

private:
    std::string format;
};

std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
    std::ostream::sentry s(os);

    if (s)
    {
        std::time_t t = std::time(0);
        std::tm const* tm = std::localtime(&t);
        std::ostreambuf_iterator<char> out(os);

        std::use_facet<std::time_put<char>>(os.getloc())
            .put(out, os, os.fill(),
                 tm, &mt.format[0], &mt.format[0] + mt.format.size());
    }

    os.width(0);

    return os;
}

int main()
{
    std::cout << timefmt("%c");
}

输出:周五9月6日20:33:31 2013