Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Guys,,, I'm try to calculated due date betwen two date but I'm can't solve this trouble. I'm found the refrence code in VB and then I'm try to translate that code to C#. Anny help could be appriciate.


What I have tried:

this isi code to calculated due date betwen two date in VB.NET
BASIC
'find maturities based on installments to ??? 
DueDate.Text = DateAdd(DateInterval.Month, Val(InstallmentsTo.Text), DateValue(RentDate.Text))


and then I'm try translate that code in C#. But this code not working
ASP.NET
<pre lang="ASP.NET">
//find maturities based on installments to ???
private void SearchDueDate()
{
System.DateTime PaymentDate;
System.DateTime RentDate;

int InstallmentsTo;
InstallmentsTo = Convert.ToInt32(txtcicilan_ke.Text);

RentDate = Convert.ToDateTime(txttgl_pinjaman.Text);
PaymentDate = Convert.ToDateTime(txttanggal_pembayaran.Text);

DueDate.Text = Convert.ToDateTime(PaymentDate - RentDate), InstallmentsTo.ToString("yyyy/MM/dd");
}
Posted
Updated 12-Jun-21 19:58pm

1 solution

First off, don;t use Val in VB, or Convert in C# to convert user input - particularly date based.
Instead use the various TryParse / TryParseExact methods and report errors to the user instead of continuing. Better still, use a calendar control for data input instead of a textbox, so the user can't enter an invalid date and access the DateTime value directly.

C#
DateTime dt;
if (!DateTime.TryParse(myTextBox.Text, out dt))
    {
    ... report problem to user ...
    return;
    }
Do the same thing for your Installments using int.TryParse, and then it's trivial:
C#
DateTime dueDate = dt.AddMonths(installments);


When you subtract two dates, you get a TimeSpan - you can't convert that to a date at all because it's just a "Number of ticks" between two points - it's like measuring two random points on a plane and subtracting them:
X = (2, 4), Y = (16, 3) - you get the distance between them as D = 14.03567 but that doesn't relate to the X or Y axes! Unless you pick a third point Z to base your "distance from" on, you can't draw it - and even then, you have an infinites number of points on a circle to chose from because distance doesn;t include any direction info!

Same this with DateA - DateB: you get a "number of days, hours, minutes" between them, but it's meaningless without a "new start point".
 
Share this answer
 
Comments
tri setia 7-Jun-21 6:26am    
thanks for the answer, I will try it.
OriginalGriff 7-Jun-21 6:45am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900