Chiwda
Chiwda

Reputation: 1364

Date not converting correctly in VB.net

It seems like I keep having problems with dates. I am using the following code:

        Dim LocalDateCultureProvider As New CultureInfo(CultureInfo.CurrentCulture.ToString)
         Dim CurrentDate As DateTime = Convert.ToDateTime(System.DateTime.Now.ToString("dd/MM/yyyy"), System.Globalization.CultureInfo.InvariantCulture)

        ExpiryDate = DateTime.ParseExact(strDate, "dd/MM/yyyy", LocalDateCultureProvider)
        If DateTime.Compare(ExpiryDate, CurrentDate) < 0 Then

MsgBox("This file has expired.")
            Exit Sub
        End If

Here I am reading strDate as a string and for one example, the value of this is "29/09/2012" However, in the ExpiryDate line it converts to #09/29/2012# so that in the comparison with today's date which is stored (correctly in my opinion) in CurrentDate as #10/6/2012# I get the If condition to be true (wrongly).

BTW, I also tried Dim LocalDateCultureProvider As New CultureInfo(System.Globalization.CultureInfo.InvariantCulture.ToString)

just to see if that was causing the problem. I am trying to build something that will work in all Cultures. No matter what the local settings are, I want to test for expiration by comparing the current system date with an expiration date which I receive as a string. Please tell me how to go about this so I can get consistent results.

TIA, Chiwda

Upvotes: 2

Views: 1673

Answers (1)

Hans Passant
Hans Passant

Reputation: 942438

No, you parse the CurrentDate incorrectly. CultureInfo.InvariantCulture expects the month before the day but you formatted it with the day first. You are writing unnecessary code, simply fix with:

    If DateTime.Compare(ExpiryDate, DateTime.Now) < 0 Then

Upvotes: 1

Related Questions