问题
In SQL Server(T-SQL) you can convert a DateTime variable to a a decimal values like this:
CONVERT(DECIMAL(20,10),@mytime)
Sample Input: 2012-07-27 08:29:20.000
Sample Output: 41115.3537037037
Is there any equivalent method of converting a DateTime in .NET(C# or VB) to the same type of decimal?
I am looking to compare times on different days.
Calculating
41115.3537037037 % 1 = .3537037037
This would allow me to easily compare times on different dates.
回答1:
It looks like this is "number of days since 1st January 1900". In which case, you'd use:
DateTime epoch = new DateTime(1900, 1, 1);
TimeSpan difference = date - epoch;
double days = difference.TotalDays;
回答2:
I know you specified you want to compare times of days (get the decimal part), but since the title is how to convert DateTime to Decimal, here's how to get the whole numeric value in one (integer AND decimal parts). You can do the following (VB.NET) and it will be equivalent to SQL Server:
Dim TimeZero As New DateTime(1900, 1, 1)
Dim MyTime As DateTime = DateTime.Parse("2012-07-27 08:29:20.000")
Dim DecResult As Decimal = DateDiff(DateInterval.Day, TimeZero, MyTime) + (MyTime.TimeOfDay.TotalSeconds / (24*3600))
来源:https://stackoverflow.com/questions/11690372/net-convert-datetime-to-decimal