1

I have date value in sql table in yyyy-mm-dd format but for single digit date and month format like, 1989-1-3 how can I display it to 1989-01-03 in asp.net labels.

nischalinn
  • 1,133
  • 2
  • 12
  • 38

4 Answers4

2

You can use .ToString() function to convert DateTime in yyyy-MM-dd

    DateTime date = new DateTime(1989,01,03);
    string strDate = date.ToString("yyyy-MM-dd");

You can assign value of strDate to asp.net label

I believe dr["DOB"] is of datatype DateTime? i.e. Nullable DateTime. If your DateTime is of Nullable then try with

lblDOB.Text = dr["DOB"].Value.ToString("yyyy-MM-dd");  

POC: .net Fiddle

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
1

Try this assuming that you are importing the value dr["DOB"].ToString(); from database as string.

#region date formatting 
string str = dr["DOB"].ToString();
//before first appearance of "-"
string result = str.Substring(0, str.IndexOf("-"));
//between two "-"
var middleDigit = str.Split('-')[1];
if (Convert.ToInt16(middleDigit) < 10)
{
    middleDigit = "0" + middleDigit;
}
//after last "-"
var last_ = str.Substring(str.LastIndexOf('-') + 1);
if (Convert.ToInt16(last_) < 10)
{
    last_ = "0" + last_;
}

lblDOB.Text = result + "-" + middleDigit.ToString() + "-" + last_.ToString();
#endregion
user4221591
  • 2,084
  • 7
  • 34
  • 68
0

You can always use var dt = DateTime.Parse(string) and after that format it as you want. Example format: dt.ToString("yyyy-MM-dd")

misticos
  • 718
  • 5
  • 22
0

If you are using ASP.NET Webforms, you can format the date as below:

<asp:Label ID="label_salary_sum" runat="server"
 Text='<%# Eval("Date", "{0:d MMM yyyy HH:mm}") %>'
/>

You can remove the Time in the format (HH:mm), if not required.

If you are assigning the value to Label from CodeBehind, then you can follow the below example:

label1.Text = date.ToString("yyyy-MM-dd");

When using DataReader, below is the correct way to handle it. Hope your DOB Field is DB is of Type DateTime:

label1.Text = Convert.ToDateTime(dr["DOB"]).ToString("yyyy-MM-dd");

For a full reference of the Date Formatting, check the link : Date Custom String Formats

Habeeb
  • 7,601
  • 1
  • 30
  • 33
  • I am getting the value from DataTable `lblDOB.Text = dr["DOB"].ToString();`, here `lblDOB` is the label name. – nischalinn May 05 '19 at 10:39
  • I tried the solution given by user4221591 and it worked. But I am not sure whether that solution is fully correct or not. Please can you help!!! – nischalinn May 07 '19 at 09:15
  • @nischalinn The solution of user4221591, if it works is well and good. but its a bit of code and string manipulation. Try my solution as well which is cleaner and more comprehensible. – Habeeb May 08 '19 at 05:15