Como criar uma calculadora de horas de trabalho precisa em C# para relatórios diários e mensais?

emily davis 0 Reputation points
2025-09-24T10:12:07.3033333+00:00

Olá, Estou desenvolvendo um projeto relacionado a uma calculadora de horas (calculadora de trabalho) onde o usuário pode inserir hora de entrada, hora de saída e intervalos, e o sistema deve calcular o total de horas trabalhadas.

Gostaria de implementar isso em C# / .NET, incluindo relatórios diários e mensais, com cálculo de horas extras (horas extras) e banco de horas (banco de horas).

Minhas principais dúvidas são:

Qual é a melhor forma de lidar com cálculos de tempo no .NET para evitar erros de formatos diferentes (HH:mm, 24h etc.)?

É melhor usar TimeSpan ou DateTime para garantir maior precisão?

Existem bibliotecas ou boas práticas recomendadas para construir esse tipo de calculadora?

Encontrei alguns exemplos úteis em https://ecalculadoradehoras.com/ e gostaria de saber se existe uma abordagem oficial recomendada para este tipo de cálculo no .NET.

Obrigado!

Developer technologies | Small BASIC
Developer technologies | Small BASIC
A programming language created by Microsoft that serves a stepping stone for beginners from block-based coding languages to more complex text-based languages.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Varsha Dundigalla(INFOSYS LIMITED) 3,810 Reputation points Microsoft External Staff
    2025-09-24T12:38:36.5166667+00:00

    Thank you for reaching out.

    1. Handle Time Formats

    Use DateTime.ParseExact() or TimeSpan.ParseExact() with a defined format ("HH:mm") to ensure consistent input and avoid parsing errors.

    DateTime clockIn = DateTime.ParseExact("09:00", "HH:mm", CultureInfo.InvariantCulture);
    DateTime clockOut = DateTime.ParseExact("18:00", "HH:mm", CultureInfo.InvariantCulture);
    TimeSpan breakTime = TimeSpan.FromMinutes(60);
    

    DateTime.ParseExact Documentation

    Custom Date and Time Format Strings

    1. Choose the Right Data Types
    • Use DateTime for specific timestamps (e.g., clock-in/out).
    • Use TimeSpan for durations (e.g., hours worked, breaks, overtime, balances).
    TimeSpan worked = (clockOut - clockIn) - breakTime;
    double totalHours = worked.TotalHours;
    

    DateTime vs TimeSpan Comparison

    TimeSpan Struct Overview

    1. Generate Daily and Monthly Reports
    • Daily: (clockOut - clockIn) - breakDuration
    • Monthly: Aggregate all daily TimeSpan values.
    List<TimeSpan> dailyHours = new List<TimeSpan>
    {
        TimeSpan.FromHours(8),
        TimeSpan.FromHours(7.5),
        TimeSpan.FromHours(9)
    };
     
    
    

    LINQ Sum Method

    LINQ Aggregate Method

    1. Overtime & Hour Bank Calculation
    • Define standard working hours (e.g., 8 hours/day).
    • Calculate overtime and monthly balance.
    TimeSpan regular = TimeSpan.FromHours(8);
    TimeSpan overtime = worked > regular ? worked - regular : TimeSpan.Zero;
     
    

    TimeSpan.Compare Method

    1. Handling Overnight Shifts

    Overnight shifts (e.g., 10 PM to 6 AM) require special handling since clockOut may be earlier than clockIn.

    if (clockOut < clockIn)
    {
        clockOut = clockOut.AddDays(1); // shift ends next day
    }
    TimeSpan worked = (clockOut - clockIn) - breakTime;
    

    Handling Overnight Shifts

    Let me know if you need any further help with this. We'll be happy to assist.

    If you find this helpful, please mark this as answered.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.