2

I have the milliseconds since epoch (windows/gregorian) for a specific time in long long int and would like to convert it to human time such as yy-mm-dd-hh-mm-ss-milli. (My platform: Windows 7, 64bit)

Unfortunately, all solutions I have found so far can't deal with the milli second (long long int) part.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Hellski
  • 65
  • 1
  • 7
  • [FileTimeToSystemTime()](http://msdn.microsoft.com/en-us/library/windows/desktop/ms724280.aspx) seems to suit your problem quite well (except it deals with hundreds of nanoseconds instead of milliseconds, and depending on which "epoch" you're referring to). – Frédéric Hamidi Mar 17 '14 at 13:20
  • I'm using windows 7 (64bit) – Hellski Mar 18 '14 at 01:53

2 Answers2

1

C++11 API is incomplete, so I had to invent a bicycle:

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

    static string format(long ts,string fmt,int cutBack=0){
        time_t tt = ts/1000;
        int microsec = ts%1000;
        struct std::tm * ptm = std::localtime(&tt);
        string fmtms=std::regex_replace(fmt, std::regex("%ms"), to_string(microsec));
        std::stringstream ss;
        ss << std::put_time(ptm, fmtms.c_str());
        string ret = ss.str();
        return ret.substr(0,ret.size()-cutBack);
    }

    std::cout << CommonUtils::format(CommonUtils::getTs(), "%Y-%m-%dT%H:%M:%S.%ms%Z")<<endl;

gives me: 2020-01-24T11:55:14.375+07, cutBack parameter is optional, it specifies how many characters to remove from the output string. It is useful when timezone format like +0700 is to long, and you just need +07.

Stepan Yakovenko
  • 8,670
  • 28
  • 113
  • 206
0

Basically, you should be able to take whatever it is that you have that writes the formatted time without milliseconds, and add the remainder of the division of the number of millisconds by 1000. This should work because leap time is always an integer number of seconds.

Assuming C++11, you can try this:

#include <chrono>
#include <iomanip>

using namespace std;
using namespace chrono;

long long int milliSecondsSinceEpoch = ... // this is your starting point
const auto durationSinceEpoch = std::chrono::milliseconds(milliSecondsSinceEpoch);
const time_point<system_clock> tp_after_duration(durationSinceEpoch);
time_t time_after_duration = system_clock::to_time_t(tp_after_duration);

std::tm* formattedTime = std::localtime(&time_after_duration);

long long int milliseconds_remainder = milliSecondsSinceEpoch % 1000;
cout <<put_time(std::localtime(&time_after_duration), "%y-%m-%d-%H-%M-%S-") << milliseconds_remainder << endl;
Martin J.
  • 5,028
  • 4
  • 24
  • 41