代码之家  ›  专栏  ›  技术社区  ›  AKIWEB

如何像Java那样获取1970年以来的当前时间戳(以毫秒为单位)

  •  185
  • AKIWEB  · 技术社区  · 12 年前

    在Java中,我们可以使用 System.currentTimeMillis() 获取自epoch时间以来的当前时间戳(以毫秒为单位)-

    当前时间和 协调世界时1970年1月1日午夜。

    在C++中,如何获得相同的东西?

    目前我正在使用它来获取当前时间戳-

    struct timeval tp;
    gettimeofday(&tp, NULL);
    long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds
    
    cout << ms << endl;
    

    这看起来对不对?

    5 回复  |  直到 10 年前
        1
  •  338
  •   Oz.    11 年前

    如果您可以访问C++11库,请查看 std::chrono 图书馆您可以使用它来获取自Unix大纪元以来的毫秒数,如下所示:

    #include <chrono>
    
    // ...
    
    using namespace std::chrono;
    milliseconds ms = duration_cast< milliseconds >(
        system_clock::now().time_since_epoch()
    );
    
        2
  •  50
  •   Alessandro Pezzato    7 年前

    由于C++11,您可以使用 std::chrono :

    • 获取当前系统时间: std::chrono::system_clock::now()
    • 获取自epoch以来的时间: .time_since_epoch()
    • 将基本单位转换为毫秒: duration_cast<milliseconds>(d)
    • 翻译 std::chrono::milliseconds 到整数( uint64_t 以避免溢出)
    #include <chrono>
    #include <cstdint>
    #include <iostream>
    
    uint64_t timeSinceEpochMillisec() {
      using namespace std::chrono;
      return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
    }
    
    int main() {
      std::cout << timeSinceEpochMillisec() << std::endl;
      return 0;
    }
    
        3
  •  49
  •   Community Mohan Dere    9 年前

    使用 <sys/time.h>

    struct timeval tp;
    gettimeofday(&tp, NULL);
    long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
    

    参考 this .

        4
  •  32
  •   kayleeFrye_onDeck    7 年前

    这个答案与 Oz.'s ,使用 <chrono> 对于C++,我没有从Oz那里得到它。。。

    我在 bottom of this page ,并稍作修改,使其成为一个完整的控制台应用程序。我喜欢用这种小东西。如果你做了大量的脚本编写,并且在Windows中需要一个可靠的工具来在实际毫秒内获得epoch,而不需要使用VB或一些不太现代、不太读者友好的代码,那就太棒了。

    #include <chrono>
    #include <iostream>
    
    int main() {
        unsigned __int64 now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
        std::cout << now << std::endl;
        return 0;
    }
    
        5
  •  14
  •   rli    11 年前

    如果使用gettimeofday,则必须强制转换为long-long,否则会出现溢出,因此不会是自epoch以来的实际毫秒数: long int msint=tp.tv_sec*1000+tp.tv_usec/1000; 会给你一个类似767990892的数字,它是纪元后8天的整数;-)。

    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;
    }