views:

311

answers:

5

String comes back from the database with a format: '00/00/0000' I need to then compare it to a date that the user has entered in the same format. How do I make the conversion and compare the two dates?

A: 

Try something like this:

String.Compare("00/00/0000", dateTime.ToString("MM/dd/yyyy"))

But perhaps a better approach would be to do this:

DateTime.Equals(yourDateTime, DateTime.Parse(databaseDateTime));
Andrew Hare
+1  A: 

You can use


Dim dateA = DateTime.ParseExact(firstDateString, @"dd\/MM\/yyyy", Null)
Dim dateB = DateTime.ParseExact(secondDateString, @"dd\/MM\/yyyy", Null)
Dim areEqual = (dateA = dateB);

Assuming that your date format is day/month/year. If it's month/day/year just swap dd and MM

emaster70
+2  A: 

Use the static ParseExact method on the DateTime structure to convert the string. You will also pass the format you want, either dd/MM/yyyy or MM/dd/yyyy depending on what format you want (the example of 00/00/0000 doesn't give any indication of what format applies for you).

casperOne
A: 

Try the following

Dim date1 = CDate(firstDateString)
Dim date2 = CDate(secondDateString)
Dim comp = date1 = date2
JaredPar
A: 

When you say compare, are you trying to analysis if the dates are the same (to the day) or within a period of a few days ? If to compare if the dates are the same then you can just compare the string or use the date.equals (as mentioned in posts before this one) , if you are trying to determine with a range you will have to use date compare

        Dim lDate1 As String = "29/03/2009"
    Dim lDate2 As String = "30/03/2009"
    Dim lPeriod As Int16 = 7

    If lDate1 = lDate2 Then
        '** Dates the same
    End If

    If Date.Equals(Date.ParseExact(lDate1, "dd/MM/yyyy", Nothing), Date.ParseExact(lDate2, "dd/MM/yyyy", Nothing)) Then
        '** The same
    End If

    If Date.Compare(Date.ParseExact(lDate1, "dd/MM/yyyy", Nothing), Date.ParseExact(lDate2, "dd/MM/yyyy", Nothing)) > (lPeriod * -1) And Date.Compare(Date.ParseExact(lDate1, "dd/MM/yyyy", Nothing), Date.ParseExact(lDate2, "dd/MM/yyyy", Nothing)) < lPeriod Then
        '** Within the period
    End If
spacemonkeys