SysTime in a Struct
Ali Çehreli
acehreli at yahoo.com
Thu Mar 1 16:00:09 PST 2012
On 03/01/2012 03:46 PM, albatroz wrote:
> Hi Ali, just tring to define a type that holds this information. It was
> just an attempt to create a type DateTime with the values from the known
> strings, I thought it was possible to create the definition directly in
> the Struct, with no need for an external function.
> edate and etime are strings that I will read in to the struct, but for
> operations with time and dates I need to create/define a DateTime type.
From that description, it looks like you can hold edate etc. as members
and produce SysTime as needed. The following demonstrates how to convert
preEv to SysTime by opCast implicitly and by sys_time explicitly:
import std.stdio;
import std.conv;
import std.datetime;
struct preEv
{
string edate; //010112
string etime; //00:00:00
string etext; //
SysTime opCast(T : SysTime)() const
{
return SysTime(DateTime(
Clock.currTime.year,
to!int(this.edate[2..4]),
to!int(this.edate[0..2]),
to!int(etime[0..2]),
to!int(etime[3..5]),
to!int(etime[6..8])));
}
SysTime sys_time() const @property
{
return to!SysTime(this);
}
}
void main()
{
auto pe = preEv("010312", "15:53:00", "The event");
// Explicit conversion
auto st0 = to!SysTime(pe);
writeln(st0);
// Casting
auto st1 = cast(SysTime)(pe);
writeln(st1);
// As a property
auto st2 = pe.sys_time;
writeln(st2);
}
If you think that you need to cache SysTime in the object itself, you
can do that for example in opCast.
On the other hand, if all you need to store is SysTime and etext, then
you need to create SysTime in the constructor:
import std.stdio;
import std.conv;
import std.datetime;
struct preEv
{
SysTime time;
string etext;
this (string edate, string etime, string etext)
{
this.time = SysTime(DateTime(
Clock.currTime.year,
to!int(edate[2..4]),
to!int(edate[0..2]),
to!int(etime[0..2]),
to!int(etime[3..5]),
to!int(etime[6..8])));
this.etext = etext;
}
}
void main()
{
auto pe = preEv("010312", "15:53:00", "The event");
writeln(pe.time);
}
Ali
More information about the Digitalmars-d-learn
mailing list