简体   繁体   中英

Coverting 9/13/2011 12:00:00 AM to 9/13/2011

I am getting this: 9/13/2011 12:00:00 AM

from my DB and I want to show like this:

9/13/2011

This is my code for this:

 litDate.Text = Obj1.DueDate.ToString();

My DueDate is of this property:

 public DateTime? DueDate { get; set; } 

尝试这个:

litDate.Text = Obj1.Date.ToString("MM/dd/yyyy");

Use the formatter "d", only if Obj1.Date is of type DateTime.

if(Obj1.DueDate.HasValue)
{
    litDate.Text = Obj1.DueDate.Value.ToString("d");
}

http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

This gives all the standard date format strings with examples.

Here is the example you want:

// Display using current (en-us) culture's short date format
DateTime thisDate = new DateTime(2008, 3, 15);
Console.WriteLine(thisDate.ToString("d"));           
// Displays 3/15/2008

The answers that explicitly format the string should not be used in any case where you might have to internationalize the date. This answer uses the culture context of the user's computer.

http://www.csharp-examples.net/string-format-datetime/

EDIT: Now that you revised your question to a COMPLETELY DIFFERENT datatype, you need to learn how Nullables work. Check .HasValue , and if so, then .Value will be a DateTime, making all the rest of these answers relevant again.

litDate.Text = Obj1.Date.ToShortDateString();

除了insta的答案,您还可以使用

litDate.Text = Obj1.Date.ToString("MM/dd/yyyy");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM