writing DateTime/TimeSpan values to a stream. Is there a shortcut?

  • Thread starter Thread starter Claire
  • Start date Start date
C

Claire

Ive been writing DateTime variables to streams the long way
binarywriter.write((int)Day); binarywriter.write((int)Hour) etc
Is there a conversion routine or some other way to shorten the process of
doing this please (eg in Delphi you just cast to a Double value and wrote
that)
I looked at DateTime.IConvertable.ToDouble, but help file said you shouldn't
use this.
I don't want to write it as a string.
thanks
 
Claire,

I assume that this can help you,

\\\
DateTime dt1 = new DateTime();
dt1 = DateTime.Now;
long lDt = (long) dt1.Ticks;
DateTime dt2 = new DateTime();
dt2 = dt2.AddTicks(lDt);
MessageBox.Show(dt2.ToString());
///

Cor
 
Some unwritten rule says that you should use type converters. There is a
DateTimeConverter and a TimeSpanConverter, unfortunately these converters
can only convert to string and and are very useful when you write
international apps with different cultures.

The reason that you shouldn't use the DateTime.Iconvertable.ToDouble() is
because you will simply get an InvalidCastException.

By the way you don't need to explicitly cast the Days en Hours properties to
an int because the data type is already int32.

Why not format your datetime as follows and write the output?
BinaryWriter.Write(<DateTimeVariable>.ToString("ddmmyyyy"));

It is true that you will save cpu cycles when you call the write method of
the binarywriter passing an int32 data type but behind the scenes it will
all be converted to byte arrays.

Gabriel Lozano-Morán
 
thanks both of you for your help
Ive gone with Cor's solution as there's no unparsing involved.
The reason I always use casting when calling the Write function is that I've
learned not to trust compilers or my memory ;) If I can visually match a
write((int)x) with a x = readint32() then Im happy.

writer.Write((Int64)LastSampled.Ticks);

Int64 i = reader.ReadInt64();
LastSampled = DateTime.MinValue.AddTicks(i);

Claire
 
Back
Top