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

400,468

Solution 1

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
);

Solution 2

use <sys/time.h>

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

refer this.

Solution 3

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<milliseconds>(d)
  • translate std::chrono::milliseconds to integer (uint64_t to avoid overflow)
#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;
}

Solution 4

This answer is pretty similar to Oz.'s, using <chrono> for C++ -- I didn't grab it from Oz. though...

I picked up the original snippet at the bottom of this page, and slightly modified it to be a complete console app. I love using this lil' ol' thing. It's fantastic if you do a lot of scripting and need a reliable tool in Windows to get the epoch in actual milliseconds without resorting to using VB, or some less modern, less reader-friendly code.

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

Solution 5

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;
}
Share:
400,468

Related videos on Youtube

AKIWEB
Author by

AKIWEB

Updated on July 08, 2022

Comments

  • AKIWEB
    AKIWEB almost 2 years

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

    the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

    In C++ how to get the same thing?

    Currently I am using this to get the current timestamp -

    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;
    

    This looks right or not?

  • Progo
    Progo over 9 years
    This returns the seconds since the epoch. Not milliseconds.
  • P1r4nh4
    P1r4nh4 over 9 years
    Nice. Add count() at the end of the line to get number of milliseconds in a fundamental type format.
  • Adem
    Adem over 9 years
    good solution, also I think it should be gettimeofday(&tp,NULL);
  • arsenal
    arsenal almost 9 years
    Will this be same if we use steady_clock instead of system_clock? Will both the epoch be same?
  • Oz.
    Oz. almost 9 years
    @lining: Both epochs are likely to be the same, but their values could be different. steady_clock will always progress forward, it is a true measure of the time since its epoch while system_clock may be a representation of the logical time since the epoch. For every leap second the two could grow further apart depending on the system's implementation.
  • arsenal
    arsenal almost 9 years
    Ok, do you know what is the epoch for steady_clock as compared to system_clock? To me epoch for the system_clock (on g++/linux) is in fact the system epoch, but for steady_clock it's something else I guess . And also let's say if we use system_clock, is there any disadvantage in leap year?
  • Oz.
    Oz. almost 9 years
    As far as I know, the epoch for each of the clocks is implementation dependent. Convention is for system_clock's to be the same as the UNIX epoch, but the spec only says it must be the system-wide real time wall clock. There is no requirement for the steady_clock to match reality, only that it only move forward.
  • rustyx
    rustyx about 8 years
    First of all, this is C, not C++. Secondly, there are problems with gettimeofday, see this for example.
  • schrödinbug
    schrödinbug over 7 years
    What's the advantage of using the c++11 chrono library as opposed to the gettimeofday?
  • Oz.
    Oz. over 7 years
    @Jason Besides gettimeofday not being available on Windows, the chrono library can give you higher resolution (gtod is limited to microseconds), provides time units in a type-safe way so the compiler can enforce unit conversions, and works with normal arithmetic operators (adding timeval structs is annoying).
  • Noitidart
    Noitidart over 7 years
    @P1r4nh4 I needed it in int but when I use .count it gives me a negative number.
  • Noitidart
    Noitidart over 7 years
    I get a negative number -560549313 this is not right, right?
  • kayleeFrye_onDeck
    kayleeFrye_onDeck over 7 years
    @Noitidart Can you tell me what platform and C++ compiler you're using? I use this thing all the time with automation tools, and have never seen a negative output o.0 More than happy to check it though. Also, is that a direct copy, or modified/integrated program? Just want to make sure it's originating from this code only.
  • Noitidart
    Noitidart over 7 years
    Ah @kayleeFrye_onDeck its because I was using int! int nowms = std::chrono::duration_cast<std::chrono::milliseconds>(std::c‌​hrono::system_clock:‌​:now().time_since_ep‌​och()).count();. I swithced that to int64_t and it works! Thanks so much for asking for more info to help!
  • Pototo
    Pototo about 7 years
    How do I convert this to int64_t?
  • Oz.
    Oz. about 7 years
    @Pototo as P1r4nh4 stated, call .count(). Check out the linked documentation for more information. en.cppreference.com/w/cpp/chrono/duration
  • Fantastory
    Fantastory over 6 years
    Javascript developers are laughing at me seeing this :(
  • ESPeach
    ESPeach about 5 years
    @Noitidart ,long int ns = std::chrono::system_clock::now().time_since_epoch().count(); appears to return the result in nanoseconds. To get it as an int, I'm doing int ms = ns / 1000000 - 1550000;, which messes with the offsets, but I'm just measuring time deltas in my project.
  • S.S. Anne
    S.S. Anne about 4 years
    unsigned long long is more portable, and __int64 is only available on MSVC.
  • Mariusz Jaskółka
    Mariusz Jaskółka almost 4 years
    there is no __int64 type in standard C++. One can use std::int64_t instead.
  • csg
    csg almost 4 years
    I suggest to use unsigned long long instead of uint64_t.
  • DragonJawad
    DragonJawad almost 4 years
    Why unsigned long long instead of uint64_t? I have a natural preference for the shorter type to type
  • Potion
    Potion over 3 years
    How can I convert this epoch ms to a datetime format where I can extract the date and time like 07/27/2020 and 20:37:46.239522 respectively?
  • Oz.
    Oz. over 3 years