Convert C# DateTime object to libpcap capture file timestamp
-
22-07-2019 - |
Question
I am stuck in converting a DateTime object to a timestamp for the libpcap capture file format (is also used by wireshark, file format definitiom) in C#. The timestamp I can't manage to convert my object to is the Timestamp in the packet (record) header (guint32 ts_sec and guint32 ts_usec).
Solution
You can do it like so:
DateTime dateToConvert = DateTime.Now;
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan diff = date - origin;
// Seconds since 1970
uint ts_sec = Math.Floor(diff.TotalSeconds);
// Microsecond offset
uint ts_usec = 1000000 * (diff.TotalSeconds - ts_sec);
OTHER TIPS
It is best to convert the Unix Epoch and your dateToConvert to UTC before any manipulation. There is a constructor for DateTime that takes a DateTimeKind for constructing the UnixEpoch, and there is a ToUniversalTime() method for the dateToConvert. If you always want Now, there is a handy DateTime.UtcNow property that takes care of that for you. The code as written shouldn't have any problems, but if you make this a function, a UTC date could be passed and working with a UTC target date and a local Unix Epoch would certainly not give the right results unless you are in GMT and not on summer time.