以下是一个C#程序示例,用于按整点拆分时间段并返回每个小时内的时长:

using System;

namespace TimeSplit
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startTime = new DateTime(2021, 1, 1, 10, 30, 0);
            DateTime endTime = new DateTime(2021, 1, 1, 14, 45, 0);

            TimeSpan duration = endTime - startTime;

            int startHour = startTime.Hour;
            int endHour = endTime.Hour;

            for (int hour = startHour; hour <= endHour; hour++)
            {
                DateTime hourStart = new DateTime(startTime.Year, startTime.Month, startTime.Day, hour, 0, 0);
                DateTime hourEnd;

                if (hour == endHour)
                {
                    hourEnd = endTime;
                }
                else
                {
                    hourEnd = new DateTime(startTime.Year, startTime.Month, startTime.Day, hour + 1, 0, 0);
                }

                TimeSpan hourDuration = hourEnd - hourStart;

                Console.WriteLine($"Hour {hour}: {hourDuration.TotalHours} hours");
            }
        }
    }
}

在上述示例中,我们假设开始时间为2021年1月1日10:30:00,结束时间为2021年1月1日14:45:00。程序将按整点拆分时间段,并计算每个小时内的时长。输出将显示每个小时的时长,例如:

Hour 10: 0.5 hours
Hour 11: 1 hours
Hour 12: 1 hours
Hour 13: 1 hours
Hour 14: 0.75 hours
``

原文地址: https://www.cveoy.top/t/topic/ivZj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录