返回顶部

[linux]获取系统时间,精确到ms

#include <time.h>
#include <sys/time.h>
#include <string>
#include <memory.h>
void getCurrentTimeString(std::string &strTime)
{
    char buf[32] = {0};
    struct timeval tv;
    struct tm tm;
    size_t len = 28;

    memset(&tv, 0, sizeof(tv));
    memset(&tm, 0, sizeof(tm));
    gettimeofday(&tv, NULL);
    localtime_r(&tv.tv_sec, &tm);
    int year = tm.tm_year + 1900;
    int month = tm.tm_mon + 1;
    int date = tm.tm_mday;
    int hh = tm.tm_hour;
    int mm = tm.tm_min;
    int ss = tm.tm_sec;
    int ms = (int)(tv.tv_usec / 1000);
    printf("Current ms is %d\n", ms);
    sprintf(buf, "%04d%02d%02d%02d%02d%02d%03d", year, month, date, hh, mm, ss, ms);
}

结果会以字符串的形式从年打印到毫秒

posted @ 2021-03-10 16:27  Swetchine  阅读(840)  评论(0)    收藏  举报