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

前端 未结 6 1032
佛祖请我去吃肉
佛祖请我去吃肉 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:55

    Since C++11 you can use std::chrono:

    • get current system time: std::chrono::system_clock::now()
    • get time since epoch: .time_since_epoch()
    • translate the underlying unit to milliseconds: duration_cast(d)
    • translate std::chrono::milliseconds to integer (uint64_t to avoid overflow)
    #include 
    #include 
    #include 
    
    uint64_t timeSinceEpochMillisec() {
      using namespace std::chrono;
      return duration_cast(system_clock::now().time_since_epoch()).count();
    }
    
    int main() {
      std::cout << timeSinceEpochMillisec() << std::endl;
      return 0;
    }
    

提交回复
热议问题