Saturday, May 14, 2011

Date and Time manipulation

Hi Folks,

Recently I was working with dates and times inside my application, and it took a long time since I figured out how to deal with dates and time.

The senario is that I have an applciation where I store DateTime values in a SQL column, and I created a Form to filter the records based on From Date and To Date.

Here is the Table structure:


And here is sample of the data inside the table:


As you can see that it consists of 2 parts, Date and Time.

Then I created the following form to filter the date column between to dates:


And to filter the dates you can use the following code:

If FromDateTextBox.Text <> "" And ToDateTextBox.Text <> "" Then
           Dim fd As DateTime = DateTime.Parse(LTrim(RTrim(FromDateTextBox.Text)))
           Dim td As DateTime = DateTime.Parse(LTrim(RTrim(ToDateTextBox.Text)))
           criteria += " AND (Convert(varchar(20), CreatedOn, 101) BETWEEN '" & fd & "'" & " And '" & td & "')"

End If


The explination:
Convert(varchar(20), CreatedOn, 101 will take the Date only part from the CreatedBy column amdf then we can compare it.

Another note that you need to put the variables values between singlr brackets 'value'.

Happy programming!
Saed

No comments:

Post a Comment