获取时间的毫秒部分

18
我需要从计时器中获取毫秒数。
    // get timer part
    time_t timer = time(NULL);
    struct tm now = *localtime( &timer );
    char timestamp[256];

    // format date time
    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d_%H.%M.%S", &now);

我想在C#中获得这样的结果:

DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss.ff")

我尝试使用%f或%F但在C++中无法使用,如何从tm获取毫秒的%f?


4
time() 返回自纪元以来经过的整数秒数。因此,显然您不能通过使用它获得亚秒级精度。请改用 gettimeofday() - Hristo Iliev
这个需要只在Windows上工作还是跨平台的? - tinman
对于Unix,可以查看我在Stack Overflow上发布的另一个答案中借用的。您可以将其反汇编以仅获取毫秒数。 - Drise
8个回答

29
#include <chrono>

typedef std::chrono::system_clock Clock;

auto now = Clock::now();
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
auto fraction = now - seconds;
time_t cnow = Clock::to_time_t(now);

然后您可以以秒为精度打印出时间戳(time_t),并打印任何小数部分所代表的内容。这可能是毫秒、微秒或其他内容。要特别获取毫秒:

auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
std::cout << milliseconds.count() << '\n';

6
这是使用 C++11 的方法。 - linquize
据我所知,您不能直接将 duration_cast 应用于时间点。 - Kyle Strand
1
@KyleStrand 你是对的。我已经发布了更正。 - bames53
1
经过进一步的了解,我认为你要找的是 time_point_cast - Kyle Strand

7

这里是另一个关于C++11的答案:

#include <iostream>
#include <iomanip>
#include <chrono>
#ifdef WIN32
#define localtime_r(_Time, _Tm) localtime_s(_Tm, _Time)
#endif

int main()
{
    tm localTime;
    std::chrono::system_clock::time_point t = std::chrono::system_clock::now();
    time_t now = std::chrono::system_clock::to_time_t(t);
    localtime_r(&now, &localTime);

    const std::chrono::duration<double> tse = t.time_since_epoch();
    std::chrono::seconds::rep milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(tse).count() % 1000;

    std::cout << (1900 + localTime.tm_year) << '-'
        << std::setfill('0') << std::setw(2) << (localTime.tm_mon + 1) << '-'
        << std::setfill('0') << std::setw(2) << localTime.tm_mday << ' '
        << std::setfill('0') << std::setw(2) << localTime.tm_hour << ':'
        << std::setfill('0') << std::setw(2) << localTime.tm_min << ':'
        << std::setfill('0') << std::setw(2) << localTime.tm_sec << '.'
        << std::setfill('0') << std::setw(3) << milliseconds
        << std::endl;
}

7

1
链接在2018-05-16是正常的。所示代码存在严重缺陷,它由4个头文件和int main(void) { char buffer[30]; struct timeval tv; time_t curtime; gettimeofday(&tv, NULL); curtime=tv.tv_sec; strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime)); printf("%s%ld\n",buffer,tv.tv_usec); return 0; }组成。使用%ld格式化微秒(a)不能满足问题格式化毫秒的目标,(b)不能准确地打印微秒。当tv_usec保持101微秒时,它会打印.101而不是.000101。—— printf("%s%.3ld\n", buffer, tv.tv_usec / 1000); - Jonathan Leffler

6
在Windows中使用Win32 API,SYSTEMTIME结构可以提供毫秒。然后,应该使用时间函数获取时间。示例代码如下:
#include <windows.h>

int main()
{
    SYSTEMTIME stime;
    //structure to store system time (in usual time format)
    FILETIME ltime;
    //structure to store local time (local time in 64 bits)
    FILETIME ftTimeStamp;
    char TimeStamp[256];//to store TimeStamp information
    GetSystemTimeAsFileTime(&ftTimeStamp); //Gets the current system time

    FileTimeToLocalFileTime (&ftTimeStamp,&ltime);//convert in local time and store in ltime
    FileTimeToSystemTime(&ltime,&stime);//convert in system time and store in stime

    sprintf(TimeStamp, "%d:%d:%d:%d, %d.%d.%d",stime.wHour,stime.wMinute,stime.wSecond, 
            stime.wMilliseconds, stime.wDay,stime.wMonth,stime.wYear);

    printf(TimeStamp);

    return 0;
} 

2
您可以使用boost::posix_time::ptime类。它的参考文档在这里。

7
我不想仅仅因为使用计时器而依赖Boost库。 - olidev

2

1
尝试使用以下代码:
struct tvTime;

gettimeofday(&tvTime, NULL);

int iTotal_seconds = tvTime.tv_sec;
struct tm *ptm = localtime((const time_t *) & iTotal_seconds);

int iHour = ptm->tm_hour;;
int iMinute = ptm->tm_min;
int iSecond = ptm->tm_sec;
int iMilliSec = tvTime.tv_usec / 1000;
int iMicroSec = tvTime.tv_usec;

2
这段代码无法编译。你可能是想要使用 struct timeval tvTime; 这段代码,然后有可能成功编译。 - Jonathan Leffler

1
在MS Visual Studio c/c++中包含sys/timeb.h并使用_ftime (_ftime_s)。检索包含time_t结构和毫秒数的struct _timeb (_ftime64),请参阅MSDN http://msdn.microsoft.com/en-/library/z54t9z5f.aspx
#include <sys/timeb.h>

struct _timeb timebuffer;
_ftime(&timebuffer);
timebuffer.millitm; //milli seconds
timebuffer.time; //the same like struct time_t

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接