Boost logo

Boost Users :

Subject: Re: [Boost-users] convert separate year, month, day, hour, minute, secs, ms to milliseconds since epoch
From: Sergey Spiridonov (sena_at_[hidden])
Date: 2019-03-11 14:44:51


On Sun, 3 Mar 2019 12:45:17 -0800
Victor Yankee via Boost-users <boost-users_at_[hidden]> wrote:

> I am using C++14 and boost 1.64.0 (could move to newest boost), and
> need to convert date and time pieces to a single value for
> milliseconds since the epoch. This is what I have:
>
> int64_t msSinceEpoch(int year,int month,int day,int hour,int
> minute,int second,int ms)
> {
> struct std::tm t;
> t.tm_sec = second;
> t.tm_min = minute;
> t.tm_hour = hour;
> t.tm_mday = day;
> t.tm_mon = month-1;
> t.tm_year = year-1900;
> t.tm_isdst = 0;
> return (1000* timegm(&t))+ms; // is timegm cross-platform?
> }
>
> Is there a better way?

time_tsec_since_epoch(int year, int month, int day,
                    int hour, int minute, int second)
{
  static const boost::posix_time::ptime
epoch(boost::gregorian::date(1970,1,1));

  boost::posix_time::ptime pt(
      boost::gregorian::date(year, month, day),
      boost::posix_time::time_duration(hour, minute, second)
  );

  boost::posix_time::time_duration since_epoch = pt - epoch;
  return since_epoch.total_seconds();
}

-- 
Best regards, Sergey Spiridonov

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net