Converting Days into Human Readable Duration Text

前端 未结 4 952
终归单人心
终归单人心 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 04:07

        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 results = new List();
    
                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());
            }
        }
    

提交回复
热议问题