C++ Time

Hi,

I am new to C++. I want to get current time in " HH:MM:ss:ms " format. How can I get it. I can get time using " %X " but in this case I need milliseconds. please help me.

Thank you.
Your options are

1. POSIX time source
2. C library time I/O for the whoel seconds
3. manual formatting of milliseconds

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <locale>
#include <sys/time.h>
int main()
{
    timeval t;
    gettimeofday(&t, NULL);
    std::string buf(40, '\0');
    std::strftime(&buf[0], buf.size(), " %H:%M:%S:", localtime(&t.tv_sec));
    std::cout << buf << t.tv_usec/1000  << '\n';
}
 00:51:12:413


...or
1) boost library time source
2) boost library time I/O either up to seconds (like with C), or use fractional seconds if you're okay with higher precision:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <locale>
#include <boost/date_time.hpp>
int main()
{
    boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); 
    std::cout.imbue(std::locale(std::cout.getloc(),
                    new boost::posix_time::time_facet(" %H:%M:%S:%f")));
    std::cout << now << '\n';
}
 01:00:55:642496
Topic archived. No new replies allowed.