ricardorios
ricardorios

Reputation: 376

How do i calculate time like numbers

Hello people i am doing an app on C# and now i am with a doubt.

I need to represent relative time, for example i have 02:30:00 i will need to say that is 2,5 hours.

How can i do that, and i need that have to be with 2 decimals here is what i have done so far, but i gives me errors with timespan

private string Horas_Matutinas(string cedula, DateTime desde, DateTime hasta)
    {
        string respuesta = "";
        DateTime resto = Convert.ToDateTime("00:00:00");
        //Llamo la conexion SQL
        SqlConnection Wdcon_usuario = new SqlConnection(WDcon);
        SqlCommand usuario = new SqlCommand();
        SqlDataReader usuarioDR = null;
        TimeSpan tiempo = Convert.ToDateTime("00:00:00") - Convert.ToDateTime("00:00:00");
        //Instancio la conexion SQL
        usuario.Connection = Wdcon_usuario;

        //Registro el Query SQL
        usuario.CommandText = "SELECT * FROM matutino WHERE " +
        "(cedula = @ID) AND " +
        "(desde >= @DESDE) AND " +
        "(hasta <= @HASTA)";
        usuario.Parameters.AddWithValue("@ID", Convert.ToInt64(cedula));
        usuario.Parameters.AddWithValue("@DESDE", Convert.ToDateTime(desde));
        usuario.Parameters.AddWithValue("@HASTA", Convert.ToDateTime(hasta));

        //Abro la conexion
        Wdcon_usuario.Open();

        //Ejecuto la consulta
        usuarioDR = usuario.ExecuteReader();

        //Empiezo el ciclo
        while (usuarioDR.Read())
        {
            TimeSpan tiempX = (DateTime)usuarioDR["tiempotrbajado"] - resto;
            tiempo = tiempo + tiempX;
            Double tiemp = Convert.ToDouble(tiempo);
            respuesta = tiempo.ToString("0.00");

        }
        //Cierro la conexion
        Wdcon_usuario.Close();
        //Termino la sentencia SQL

        //int i = 0;
        int total = 8;
        int caracteres = respuesta.Length;
        int restantes = total - caracteres;

        //respuesta.PadLeft(restantes, "0");


        string s = new String('0', restantes) + respuesta;
        return s;
    }

Upvotes: 1

Views: 253

Answers (5)

Adam S
Adam S

Reputation: 3125

It looks like you need the difference between two times here, this example might help you out.

DateTime now = DateTime.Now;
DateTime later = DateTime.Now.AddHours(2.5);
double diff = (later - now).TotalHours;
var x = String.Format("{0:0.00}", diff);

Also, you can create resto and tiempo without using Convert. Instead, you can use:

DateTime resto = DateTime.Now.Date;
TimeSpan tiempo = new TimeSpan();

Upvotes: 1

Rodrigo Montemayor
Rodrigo Montemayor

Reputation: 31

You could do it in SQL Server (I assume you are using SQL Server)... this is a ugly example but you could append the results or just convert them:

SELECT SUBSTRING(CAST(CONVERT(TIME, GETDATE()) AS char(20)), 0, 3) AS horas, CAST(SUBSTRING(CAST(CONVERT(TIME, GETDATE()) AS char(20)), 4, 2) AS float) / 60 * 100 AS minutos

Lots of functions, but thats the idea. Get the date (I use getDate(), you could use your column)... convert it to time (in my case 'cause I don't want the date for the example). Cast it to char so we can substring it to get hours or minutes, and in minutes y cast as float to divide and get the relation (30 = .5).

Just an idea.

Upvotes: 0

Nathan Hase
Nathan Hase

Reputation: 659

You probably need to get the TimeSpan like this: TimeSpan tiempX = (TimeSpan)((DateTime)usuarioDR["tiempotrbajado"] - resto);

Then format the result using one of the Standard TimeSpan Format Strings: http://msdn.microsoft.com/en-us/library/ee372286.aspx

Upvotes: 0

KeithS
KeithS

Reputation: 71565

The TimeSpan.TotalHours property looks like what you want. It returns the total time value of the TimeSpan expressed as whole and fractional hours. You can then round that value (it'll be a double) to however many decimal places you may need with Math.Round(), and format it for display using the overload of ToString() that takes a CultureInfo, or a specified format string.

Upvotes: 0

gSamp
gSamp

Reputation: 93

Try replacing this Line

Double tiemp = Convert.ToDouble(tiempo);

With this

Double tiemp = tiempo.TotalHours;

Timespan.TotalHours will return the timespan as whole and fractional hours which is what you appear to want

Upvotes: 1

Related Questions