C # Is it possible to convert DateTime format to integer or float?

I have problems here. Some research on google, but i can't find what i'm looking for. I am trying to query two inputs (datetimes) in the format hh: mm, subtract one for the other, and then return the result of this value in minutes. The problem is that I want to return this value as an integer, and I cannot find the right way to do this. In C / C ++, I would not have such problems ... In any case, here is a snippet of what I am saying.

private int DuraçaoTreino(DateTime dtInicioTreino, DateTime dtFimTreino, int dtDuraçao) { Console.WriteLine("Introduza a hora de inicio (hh:mm): "); dtInicioTreino = Convert.ToDateTime(Console.Read()); Console.WriteLine("Introduza a hora de fim (hh:mm): "); dtFimTreino = Convert.ToDateTime(Console.Read()); dtDuraçao = (dtFimTreino - dtInicioTreino); // duração da sessão de treino dtDuraçao = Convert.ToDecimal(Console.Read()); return dtDuraçao; } 

And that is pretty much ... I'm new to C #, so if you see something wrong, please be kind.

Thanks in advance.

+4
source share
3 answers

What you are talking about is TimeSpan :

 DateTime dtBegin = new DateTime(2011,5,1,22,0,0) ; // 10pm 1 May 2011 DateTime dtEnd = new DateTime(2011,5,1,23,0,0) ; // 11pm 1 May 2011 TimeSpan tmElapsed = dtEnd - dtBegin ; // tmElapsed is a TimeSpan with a value of 60 minutes 

To return the minutes, do the following:

 int elapsedTimeInMinutes = (int) Math.Round( tmElapsed.TotalMinutes , 0 ,MidpointRounding.ToEven ) ; 
+3
source
 var timeInMinutes = new DateTime(2011, 12, 25).Subtract(new DateTime(2010, 1, 1)).TotalMinutes; 

Instead of creating DateTime objects using the constructor you use, you can use DateTime.Parse or, better, DateTime.ParseExact to convert strings to date. (I know that I only use dates, but you only choose to use temporary parts if you want)

+2
source

Convert DateTime objects to TimeSpan, subtract and call TimeSpan.TotalMinutes (or smth like this - don't have VS at hand):

 DateTime dt1, dt2; 

// Assign some dates, then:

 TimeSpan ts = dt2 - dt1; 

double minutes = ts.TotalMinutes;

0
source

All Articles