Converting Days into Human Readable Duration Text

前端 未结 4 906
终归单人心
终归单人心 2021-01-14 03:17

Given an amount of days, say 25, convert it into a duration text such as \"3 Weeks, 4 Days\"

C# and F# solutions would both be great if the F# variation offers any i

4条回答
  •  醉梦人生
    2021-01-14 03:51

    This is a recursive solution. Note that a duration only really makes sense measured against a particular point in time on a given calendar because month and year lengths vary. But here is a simple solution assuming fixed lengths:

    let divmod n m = n / m, n % m    
    
    let units = [
        ("Centuries", TimeSpan.TicksPerDay * 365L * 100L );
        ("Years", TimeSpan.TicksPerDay * 365L);
        ("Weeks", TimeSpan.TicksPerDay * 7L);
        ("Days", TimeSpan.TicksPerDay)
    ]
    
    let duration days =
        let rec duration' ticks units acc =
            match units with
            | [] -> acc
            | (u::us) ->
                let (wholeUnits, ticksRemaining) = divmod ticks (snd u)
                duration' ticksRemaining us (((fst u), wholeUnits) :: acc)
        duration' (TimeSpan.FromDays(float days).Ticks) units []
    

提交回复
热议问题