简体   繁体   中英

C# Convert Date To Double

I have written a function in VBA which creates a code from the properties of a file. I need a developer to do the same in C# on their end.

The developer says it is not possible to do the same in c#.

So in VBA, part of my process is to convert a date to a double. The way VBA does this is to basically count the number of days between the given date and 1 Jan 1900. So 19 Mar 2014 would be a double value of 41,717.

How would I say write a function in C# (not a language I am familiar with) that would convert a date data type to the number of days that have passed since 1 January 1900?

Any help would be appreciated.

Subtracting two DateTime s gives you a TimeSpan . You can just use TimeSpan.TotalDays to get the number of days between two dates:

double days = (DateTime.Today - new DateTime(1900,1,1)).TotalDays;

If the DateTime has a time component it will be represented as fractions of a day, so for example:

 // current date and time (16:24:15)
 (new DateTime(2014, 3, 18, 16, 24, 15) - new DateTime(1900,1,1)).TotalDays

would give you 41714.6835069444

Note that the result is 2 days different that using CDbl() in VBA since a date in VBA is represented by the number of days since 12/30/1899 rather than 1/1/1900.

使用.net DateTime方法ToOADate()将返回一个表示OLE自动化日期精度VBA使用此相同格式将一个日期表示为double型

I got exactly 3 days difference. Which might be because I'm in NZ at GMT + 12. Or it might be because I was multiplying a double by "TicksPerDay" and .Net doesn't allow for some strange numbers.

DateTime.FromOADate(vbaTime) was the perfect solution for me moving dates between MS Access and C#.

Incidentally, I suspect that this is a result of the "date calculation issue" that Joel Spolsky refered to: http://www.joelonsoftware.com/items/2006/06/16.html

when discussing Lotus notes compatibility in Excel as the program manager at Microsoft.

How about this, without using OLE Automation:

'get time elapsed since some earlier point in time, such as midnight today
Dim tim As TimeSpan = Now.Subtract(Today)

'calc the time elapsed in fractional seconds
'note that tim.Seconds only provides whole seconds, so add tim.Milliseconds
Dim tsec As Double = tim.Hours * 3600 + tim.Minutes * 60 + tim.Seconds + tim.Milliseconds / 1000 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM