Datetime: convert and subtract?
I have some problem with my project.
1) I want to convert String (ex : "14/03/1987",...) to system datetime
2) I want this function : Subtract(date1,date2)
==> result: if subtract(date1, date2) > "1 month" then ......do something
else if .........do something
Please help me.
Thanks a lot.
Re: Datetime: convert and subtract?
You can use the Date.Parse or Date.ParseExact method to convert your String to a Date. Just note that, if there is any chance that the string won't contain a valid date, you MUST implement exception handling or your app could crash.
Once you've got two Date objects you have some options but, in your case, I'd suggest that the best option would be:
vb.net Code:
If date2 > date1.AddMonths(1) Then
Re: Datetime: convert and subtract?
You can use timespan method. it is very simple.
Code:
Dim d1 As DateTime = Format(Now.Date, "MM/dd/yyyy") ' Format day of VIETNAM
Dim d2 As DateTime = txt5ngayno.Text.Substring(20, txt5ngayno.Text.Length - 20)
'....
Dim ts As TimeSpan
ts = d1.Subtract(d2)
txt5tuoino.Text = ts.Days & " " & " ngày "
are you fine ?
Re: Datetime: convert and subtract?
Quote:
Originally Posted by
manhit45
You can use timespan method. it is very simple.
Code:
Dim d1 As DateTime = Format(Now.Date, "MM/dd/yyyy") ' Format day of VIETNAM
Dim d2 As DateTime = txt5ngayno.Text.Substring(20, txt5ngayno.Text.Length - 20)
'....
Dim ts As TimeSpan
ts = d1.Subtract(d2)
txt5tuoino.Text = ts.Days & " " & " ngày "
The problem with using a TimeSpan in this situation is that it can't tell you anything above the number of days a period contains. A TimeSpan is not relative to any particular point in time so if a TimeSpan is equal to 30 days then is that more than a month, less than a month or a month exactly? There's no way to know because you have no point of reference. That's why using the AddMonths method of the Date is a better option for this particular case. If you were interested in a number of days then the TimeSpan would be the way to go.
Re: Datetime: convert and subtract?
Ok, i know that. i only want to add other way in addition to your way.
Thanks for explanation.
Re: Datetime: convert and subtract?