views:

370

answers:

2

Hi there

Call me a noob, but 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 here: http://wiki.wireshark.org/Development/LibpcapFileFormat) 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).

may a friendly experienced programmer help me...

+4  A: 

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);
Reed Copsey
It works. Thank you very much =).
Emiswelt
A: 

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.

Matt Schuette