C#时长格式化器

对不同的时长以不同的格式生成字符串


        public class TimeDurationFormatter
        {
            public static string FormatDuration(int totalSeconds)
            {
                TimeSpan timeSpan = TimeSpan.FromSeconds(totalSeconds);

                string durationString;

                if (timeSpan.TotalDays >= 1)
                {
                    durationString = $"约{timeSpan.Days}天{timeSpan.Hours}小时";
                }
                else if (timeSpan.TotalHours >= 1)
                {
                    durationString = $"约{timeSpan.Hours}小时{timeSpan.Minutes}分钟";
                }
                else if (timeSpan.TotalMinutes >= 1)
                {
                    durationString = $"{timeSpan.Minutes}分钟{timeSpan.Seconds}秒";
                }
                else
                {
                    durationString = $"{timeSpan.Seconds}秒";
                }

                return durationString;
            }
        }

        public static void TestFormatDuration()
        {
            // 测试用例
            int[] testCases = { 3665, 86400, 5400, 120, 30, 5 };

            foreach (int seconds in testCases)
            {
                string duration = TimeDurationFormatter.FormatDuration(seconds);
                Console.WriteLine($"{seconds}秒 对应的时长为: {duration}");
            }
        }

你可能感兴趣的:(c#,开发语言)