Home > database >  Having problem to convert Vb method into C# method
Having problem to convert Vb method into C# method

Time:02-28

I wont to convert this VB method below into c# method. This method should calculate number of days for Rent and then multiply that number with txtRate textbox, so I can get the final number (txtTotal) which can be after stored into data grid view.

VB Method

Sub GetTotal()
    Try
        Dim day As Integer
        day = DateDiff("d", Now.Date.ToString("MM-dd-yyyy"), DateTimePicker1.Value.ToString("MM-dd-yyyy"))
        day  = 1
        lblDay.Text = day
        txtTotal.Text = Format(day * CDbl(txtRate.Text), "#,##0.00")
    Catch ex As Exception
        txtTotal.Text = "0.00"
    End Try
End Sub

I did not find any similar method like vb DateDiff is and that is the main problem.

CodePudding user response:

You can just subtract one DateTime from another. It realizes a TimeSpan, which has a TotalDays property:

//if the date time picker date is in the future 
(dateTimePicker1.Value - DateTime.Now).TotalDays

TotalDays is a decimal number, like 1.5. One thing to note with a lot of DateDiff functions (SQLServer, VBA, and maybe hence also VB - I can't quite remember) is that they give you the number of times the interval has changed between the dates which is subtly different to a time span

For example asking SQLServer's DateDiff for the years between 2020-12-31 23:59:59 and 2021-01-01 00:00:01 will say "1 year" because the year rocker up from 2020 to 2021, even though only 2 seconds have passed between the two dates

As such if you do specifically need that "imprecise" behavior, you might want to carefully assess whether a TineSpan route (which is very accurate and would give a TotalDays of eg 0.0000235 for the 2 seconds example a live whereas DateDiff would have said 1)

CodePudding user response:

I managed to solve firs part of the problem. My current solution is this :

private void GetTotal() {

       try

        {
            DateTime d1 = DateTime.Now;
            DateTime d2 = dtReturn.Value;

            TimeSpan diff = d2.Subtract(d1);

            lblDay.Text = diff.Days.ToString("0.00"); //here I get number of Rent days
        }
        catch (Exception)
        {
            txtTotal.Text = "0.00";
        }
    }

                                                

Now I need to multiply Value from lblDay with another txt fild (txtRate) so I can get a Total Value wich is stored into txtTotal Field. After I need to store transaction into data grid view

  • Related