How to print time in format: 2009‐08‐10 18:17:54.811

前端 未结 7 2054
旧时难觅i
旧时难觅i 2020-11-27 12:24

What\'s the best method to print out time in C in the format 2009‐08‐10 
18:17:54.811?

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 12:56

    None of the solutions on this page worked for me, I mixed them up and made them working with Windows and Visual Studio 2019, Here's How :

    #include 
    #include  
    #include 
    
    static int gettimeofday(struct timeval* tp, struct timezone* tzp) {
        namespace sc = std::chrono;
        sc::system_clock::duration d = sc::system_clock::now().time_since_epoch();
        sc::seconds s = sc::duration_cast(d);
        tp->tv_sec = s.count();
        tp->tv_usec = sc::duration_cast(d - s).count();
        return 0;
    }
    
    static char* getFormattedTime() {
        static char buffer[26];
    
        // For Miliseconds
        int millisec;
        struct tm* tm_info;
        struct timeval tv;
    
        // For Time
        time_t rawtime;
        struct tm* timeinfo;
    
        gettimeofday(&tv, NULL);
    
        millisec = lrint(tv.tv_usec / 1000.0);
        if (millisec >= 1000) 
        {
            millisec -= 1000;
            tv.tv_sec++;
        }
    
        time(&rawtime);
        timeinfo = localtime(&rawtime);
    
        strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", timeinfo);
        sprintf_s(buffer, 26, "%s.%03d", buffer, millisec);
    
        return buffer;
    }
    
    

    Result :

    2020:08:02 06:41:59.107

    2020:08:02 06:41:59.196

提交回复
热议问题