Reputation: 29
Below is my attempt in creating a function that calculates the difference between two dates.
let test date =
let today = DateTime.Now
let fromdate = DateTime.Parse(date)
let count = Convert.ToInt32(today - fromdate)
date
The above code prompts the error
System.InvalidCastException: Unable to cast object of type
'System.TimeSpan' to type 'System.IConvertible'.
Upvotes: 1
Views: 2878
Reputation: 6324
The difference between two DateTimes will give you a TimeSpan object, on which you can further operate. This should be the last statement in your function, as it will be used as the return value. You can check the MS docs in the link for the various properties and methods. Strictly speaking, this is part of the BCL, so it's rather .NET than just F# (you would do the same in VB or C#). If you want to further refine your function you should examine DateTime.TryParse
as well and handle the possibility of not receiving a valid date.
open System
let test date =
let today = DateTime.Now
let fromdate = DateTime.Parse(date)
(today - fromdate).Days
test "2017/12/31" // val it : int = -325
Upvotes: 2
Reputation: 6556
You don't need to convert the time span resulting from applying the "minus" operator to two dates. The screenshot below is my attempt at fixing your function and an example of value it returns.
Upvotes: 0