Ashir K.
Ashir K.

Reputation: 121

Converting string hours and minutes into Days/Hours/Minutes in C#?

I have the sum of the working duration of Employees in a specific period. I need to convert this Working Duration into days, hours and minutes. The problem is my day is equal to 9 Hours, not 24 Hours. Means I am dividing my Duration with 9. But the result I am getting is in points and I can't convert to my yearning format. Following is my code:

var Durations = TimeSpan.FromMinutes(db.Attendances.Where(x => x.EmployeeId == id)
                .Sum(x => TimeSpan.Parse(x.Duration).TotalMinutes));

var TotalDuration = string.Format("{0}:{1}", Durations.TotalHours, Durations.Minutes);

This one is working absolutely fine. I am getting results in the following format:

H:M
8:5
12:7
19:15

The problem is I need to convert hours into Days and Hours when I divide it by 9. E.g. 19. If I divide 19 by 9 I get 2.111111 Means 2 Days and 1 Hour. How can I get the answer in days and hours format?

Upvotes: 0

Views: 1417

Answers (3)

Ali Akram
Ali Akram

Reputation: 39

int totalmins = 5000; // given input
int hourPerDay = 9 // given input
int dayHour = 60 * hourPerDay;
int days = totalmins / dayHour;
int hours = (totalmins % dayHour) / 60;
int mins = tot_mins % 60;   

Upvotes: 0

Jend DimShu
Jend DimShu

Reputation: 97

I think this should answer your question:

   TimeSpan s = new TimeSpan(20,0, 0);
        int day = (int)s.TotalHours / 9;
        int hour = (int)s.TotalHours % 9;
        Console.WriteLine($"the duration in day is {day } hour {hour}");

Upvotes: 1

Mazaher Bazari
Mazaher Bazari

Reputation: 421

You can add an extension method to TimeSpan.

public static (int day,int hour) GetDayAndHour(this TimeSpan timeSpan,int dayDuration == 9) {

        var  number= timeSpan.TotalHours/dayDuration;
        int day  = (int)Math.Truncate(number);
        int hour= (int)Math.Truncate((number-day)*10);
        return (day,hour);
}

I use C#7 tuple.If you use previous version, create costume datatype or use Tuple<int, int>.

Upvotes: 0

Related Questions