将天数转换为人类可读持续时间文本

时间:2008-11-17 20:43:28

标签: c# f#

给定天数,比如25,将其转换为持续时间文本,例如“3周,4天”

如果F#变体提供了超过C#的任何改进,那么C#和F#解决方案都会很棒。

编辑:解决方案应该延续数周,包括数月和数年。包括几个世纪等在内的奖励积分。如果它有些可配置,则额外奖励,这意味着您可以告诉该方法排除周数的标准化。

4 个答案:

答案 0 :(得分:5)

String.Format("{0} Weeks, {1} days", days / 7, days % 7);

答案 1 :(得分:1)

这是递归解决方案。请注意,对于特定日历上的特定时间点,持续时间才真正有意义,因为月份和年份长度会有所不同。但这是一个假设固定长度的简单解决方案:

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

答案 2 :(得分:0)

    public class UnitOfMeasure {
        public UnitOfMeasure(string name, int value) {
            Name = name;
            Value = value;
        }

        public string Name { get; set; }
        public int Value { get; set; }

        public static UnitOfMeasure[] All = new UnitOfMeasure[] {
            new UnitOfMeasure("Year", 356),
            new UnitOfMeasure("Month", 30),
            new UnitOfMeasure("Week", 7),
            new UnitOfMeasure("Day", 1)
        };

        public static string ConvertToDuration(int days) {
            List<string> results = new List<string>();

            for (int i = 0; i < All.Length; i++) {
                int count = days / All[i].Value;

                if (count >= 1) {
                    results.Add((count + " " + All[i].Name) + (count == 1 ? string.Empty : "s"));
                    days -= count * All[i].Value;
                }
            }

            return string.Join(", ", results.ToArray());
        }
    }

答案 3 :(得分:0)

这是基于之前发布的C#版本的F#版本。主要的区别在于它是适用的而不是命令式的(没有可变的变量)。

#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)