Converting Days into Human Readable Duration Text

前端 未结 4 900
终归单人心
终归单人心 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:48

    Here's an F# version based on the previously posted C# version. The main difference is it's applicative rather than imperative (no mutable variables).

    #light
    let conversions = [|
        365, "Year", "Years"
        30, "Month", "Months"
        7, "Week", "Weeks"
        1, "Day", "Days" |]
    let ToDuration numDays =
        conversions
        |> Array.fold_left (fun (remainDays,results) (n,sing,plur) ->
            let count = remainDays / n
            if count >= 1 then 
                remainDays - (count * n),
                  (sprintf "%d %s" count (if count=1 then sing else plur)) :: results
            else
                remainDays, results
        ) (numDays,[])
        |> snd |> (fun rs -> System.String.Join(", ", List.rev rs |> List.to_array))
    printfn "%s" (ToDuration 1008)    
    

提交回复
热议问题