0

i am facing problem when i'm getting difference between 2 dates. For example, '9/11/2016' minus '7/11/2016' the result comes out 62. Why? Anyone can help me please? Any response is appreciated, Thanks in advance. :)

Protected Sub txtReturnDate_TextChanged(sender As Object, e As EventArgs) Handles txtReturnDate.TextChanged

    Dim d1 As DateTime = txtArriveDate.Text
    Dim d2 As DateTime = txtReturnDate.Text

    Dim days As Integer = (d2 - d1).TotalDays
    lblDuration.Text = days.ToString()
End Sub
assylias
  • 321,522
  • 82
  • 660
  • 783
Zhen Chua
  • 5
  • 4
  • Some context may help. Is this VB.Net? Are you sure you have the date and month the way round you think they are? What do you expect? – doctorlove Nov 07 '16 at 13:06
  • Hi, yes it is vb.net i expect to get like 2 if the date is '9/11/2016 and '7/11/2016''. I think i get the date correctly from my jquery datepicker. – Zhen Chua Nov 07 '16 at 13:17
  • Does it really accept a string. Consider trying the `Parse` method and being explicit about the format you are using in the string: https://msdn.microsoft.com/en-us/library/system.datetime.parse(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1 – doctorlove Nov 07 '16 at 13:41
  • 2
    it could be 11 july 2016 and 11 sep 2016... – Mukul Varshney Nov 07 '16 at 14:17
  • i see thats why the result is wrong the confusion during conversion – Zhen Chua Nov 07 '16 at 14:34
  • You should turn on Option Strict - `Dim d1 As DateTime = txtArriveDate.Text` wont compile – Ňɏssa Pøngjǣrdenlarp Nov 07 '16 at 23:47

1 Answers1

1

62 = days between 11 july 2016 and 11 sep 2016. Try below for date conversion. This will avoid the confusion of day vs month.

Dim dt As DateTime = DateTime.ParseExact(txtArriveDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Mukul Varshney
  • 3,131
  • 1
  • 12
  • 19