How to get current time and date in C++?

后端 未结 24 1524
刺人心
刺人心 2020-11-22 06:55

Is there a cross-platform way to get the current date and time in C++?

24条回答
  •  灰色年华
    2020-11-22 07:19

    Yes and you can do so with formatting rules specified by the currently-imbued locale:

    #include 
    #include 
    #include 
    
    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 out(os);
    
            std::use_facet>(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");
    }
    

    Output: Fri Sep 6 20:33:31 2013

提交回复
热议问题