How to get current timestamp in milliseconds since 1970 just the way Java gets

前端 未结 6 1046
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 11:42

In Java, we can use System.currentTimeMillis() to get the current timestamp in Milliseconds since epoch time which is -

the difference, m

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 11:57

    If using gettimeofday you have to cast to long long otherwise you will get overflows and thus not the real number of milliseconds since the epoch: long int msint = tp.tv_sec * 1000 + tp.tv_usec / 1000; will give you a number like 767990892 which is round 8 days after the epoch ;-).

    int main(int argc, char* argv[])
    {
        struct timeval tp;
        gettimeofday(&tp, NULL);
        long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
        std::cout << mslong << std::endl;
    }
    

提交回复
热议问题