转换天进人类可读的文本期限 [英] Converting Days into Human Readable Duration Text

查看:73
本文介绍了转换天进人类可读的文本期限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于天量,比如25,将其转换成持续的文字,如3周,4天

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

C#和F#的解决方案将同时为伟大如果F#的变化提供了超过C#有任何改善。

C# and F# solutions would both be great if the F# variation offers any improvement over C#.

编辑:该解决方案应扩大过去几周,包括几个月甚至几年。奖励积分,包括世纪等。额外的好处,如果它是有些配置的,这意味着你可以告诉的方法来排除周正常化。

The solution should expand past weeks to include months and years. Bonus points for including centuries and so on. Extra bonus if it is somewhat configurable, meaning you can tell the method to exclude the normalization of weeks.

推荐答案

这是一个递归解决方案。注意,一个持续时间只有真正使针对一个特定的时间点上测量一个给定的日历因为月和年的长度变化感。但是,这里有一个简单的解决方案,假设固定长度的:

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 []

这篇关于转换天进人类可读的文本期限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆