On Friday, 29 March 2013 at 14:03:34 UTC, Steven Schveighoffer
wrote:
Another example, I once had to convert a long type which
represented
Unix time into DateTime. Here's the code to do it:
return
cast(DateTime)SysTime(unixTimeToStdTime(cast(int)d.when.time));
I have three comments here:
1. unixTimeToStdTime should take ulong.
2. There should be a shortcut for this.
Note on Windows, given a SYSTEMTIME we can do:
return cast(DateTime)SYSTEMTIMEToSysTime(t);
We need an equivalent unixTimeToSysTime, and in fact, I think
we can get rid of unixTimeToStdTime, what is the point of that?
3. I HATE "safe" cast conversions. If you want to make a
conversion, use a method/property. I don't even know why D
allows overloading casting. Casts are way too blunt for this.
The code should be:
return unixTimeToSysTime(d.when.time).asDateTime;
I think anything-to-anything conversion is possible.
T toTime(F,T)(F fromValue, TimeZone zone=Utc)
{
// first make an intermediate value
// the source type needs to support toSysTime method
// also it should not be a primitive type
SysTime temp = fromValue.toSysTime(zone);
// also define an extension method for SysTime
// for conversion to this time type
return temp.toTime!(T);
}
unix time will need a wrapper for strong typing
struct UnixTime { int value; }
SysTime toSysTime(UnixTime fromValue, TimeZone zone=Utc)
{ return SysTime(unixTimeToStdTime(fromValue.value), zone); }
so conversion is
return UnixTime(d.when.time).toTime!DateTime;
may be it can be reduced to
return to!DateTime(UnixTime(d.when.time));