nischalinn
nischalinn

Reputation: 1175

yyyy-mm-dd date format when date and month are single digit

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.

Upvotes: 1

Views: 2095

Answers (4)

Habeeb
Habeeb

Reputation: 8007

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

Upvotes: 0

user4221591
user4221591

Reputation: 2150

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

Upvotes: 1

Prasad Telkikar
Prasad Telkikar

Reputation: 16059

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

Upvotes: 2

misticos
misticos

Reputation: 787

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

Upvotes: 0

Related Questions