Kevin Zhou
Kevin Zhou

Reputation: 33

Display C# DateTime in HTML Date Input

I get a DateTime in SQL Server DataBase and want to display it in Input:

<input class="form-control" type="date" name="ExpireDate" id="expiredate" runat="server" value="31/12/2016" style="height: 30px; width: 267px">

and here is my C# codes:

Medicine med = new Medicine(); 
int a = GridView1.SelectedIndex; 
med.ID = int.Parse(GridView1.DataKeys[a].Value.ToString()); 
DataProcess bal = new DataProcess(); DataTable dt = bal.getInfo(med)
expiredate.Value = Convert.ToDateTime(dt.Rows[0][5]).ToString("dd/MM/yyyy");

I put a break point just after the last line , I saw dt.Rows[0][5] got "{2017/5/31 0:00:00}" and expiredate.Value got "31/05/2017",but it just shows nothing without error in webpage. And this DateTime record is inserted into DataBase through exactly the same Input, I just don't know how to display it in the same Input when I pull it out from DataBase.

First time to ask, many thanks!

Upvotes: 3

Views: 14852

Answers (2)

Ananda G
Ananda G

Reputation: 2539

It seems that you are pushing a date inside a input field which is date type. But this won't work. Because html do not support the default value for raw date format. So you have to customize the date field using a javascript. However if ou take any help from Razor Html helper then you would be able to do this either not as you are on .NET framwork. Easily you can take help from previous answers jQuerydatepicker, here you can set a default date through javascript, which will show on your input field.

Upvotes: 0

Mahbub Moon
Mahbub Moon

Reputation: 511

The problem here is the format of html date input and asp.net DateTime doesn't match. Html date input displays mm/dd/yyyy but the format behind is yyyy-MM-dd.

Try using expiredate.Value = Convert.ToDateTime(dt.Rows[0][5]).ToString("yyyy-MM-dd");

Hope this helps.

Upvotes: 8

Related Questions