Unni R
Unni R

Reputation: 61

how to retrieve date format data from database

How to retrieve date format data from database to textbox.my code attached here

SqlDataReader sdr=sda.ExecuteReader() if (sda.Read()==True)
Txtdateofbirth=sdr.GetValue(2).ToString();

but time also showing in text box..how to get date only in text box

Upvotes: 0

Views: 2948

Answers (3)

Amnesh Goel
Amnesh Goel

Reputation: 2655

Well you need to change your query that you are firing on your database. Select the right format that you need.

You can try this .. convert(varchar(20),getdate(),101)This will return in mm/dd/yyyy

102 - yyyy.mm.dd
103 - dd/mm/yyyy
104 - dd.mm.yyyy
105 - dd-mm-yyyy

etc.

Use Replace(convert(varchar(11),getdate(),106), ' ','/') for DD/Mon/YYYY format.

Upvotes: 0

SBurris
SBurris

Reputation: 7448

There are two ways that you can approach this:

Doing it in the database layer at the time you do query (preferred):

Example (works with MS SQL Server)

SELECT Id, Name, DateOfBrith, CONVERT(datetime, DateOfBirth, 101)
FROM Person

I am not sure what database engine you are using, check the documentation for that version.

If you wanted to do this in your code/business layer (BL) then you could do this:

SqlDataReader sdr=sda.ExecuteReader(); 
if (sda.Read()==True)
{
    Txtdateofbirth=sdr.GetValue(2).ToString();
    DateTime dateObject;
    if (DateTime.TryParse(Txtdateofbirth, out dateObject) == false)
    {
        //Did not recieve date value back, do something
    }
    var displayDate = dateObject.ToString("MM/dd/yyyy");
}

Upvotes: 1

mp3ferret
mp3ferret

Reputation: 1193

You can get the date only as a string by using ToString() with a custom format.

eg.

DayDate.ToString("yyyy-MM-dd").

Upvotes: 1

Related Questions