MySQL time, datetime and timestamp types do not preserve milliseconds. However, MySQL does support storing datetime information using decimal(17,3). I came up with the following c# code to convert back and forth between (.net) datetime and decimal.
public static decimal ToDecimalForMySql(System.DateTime dateTime)
{
return dateTime.Year * 10000000000m + dateTime.Month * 100000000m + dateTime.Day * 1000000m + dateTime.Hour * 10000m + dateTime.Minute * 100m + dateTime.Second + dateTime.Millisecond * 0.001m;
}
public static System.DateTime FromDecimalForMySql(decimal dateTime)
{
long truncated = (long) Math.Truncate(dateTime);
int msecs = (int) (1000 * (dateTime - truncated));
long month;
int day, hour, minute, second;
return new System.DateTime((int) Math.DivRem(truncated, 10000000000, out month), Math.DivRem((int) month, 100000000, out day),
Math.DivRem(day, 1000000, out hour), Math.DivRem(hour, 10000, out minute), Math.DivRem(minute, 100, out second), second, msecs);
}
Is there a more efficient way of doing this, perhaps using bit fields to convert back from decimal to datetime?