开发者

How to remove trailing characters after a blank space in C#?

I've a string, '12/10/2开发者_开发知识库010 00:00:00'. How do I show this as ''12/10/2010' using C#?


You might try:

EDIT:

DateTime d;
DateTime.TryParse("12/10/2010 00:00:00", d);
d.ToString("MM/dd/yyyy");


Everyone else has answered the question directly, however I have a feeling that what you really need is to become familier with the various ways System.DateTime provides to generate a string representation:

DateTime.ToShortDateString

DateTime.ToShortTimeString

DateTime.ToString(string)


This takes the first half of your string before the space:

   string formatedDt = "12/10/2010 00:00:00".Split(' ')[0];


string s =  "12/10/2010 00:00:00";
s = s.Substring(0,s.IndexOf(" ");


Check out String.Split


"12/10/2010 00:00:00".Split(' ')[0]

this returns the whole string if it doesn't contain a space.

Or if you need other behavior in case of a missing space you can do this:

string s =  "12/10/2010 00:00:00";
int spaceIndex=s.IndexOf(" ");
if(spaceindex>=0)
{
    return = s.Substring(0,spaceIndex);
}
else
{
    //Handle the case without space here
    //For example throw a descriptive exception
    throw new InvalidDataException("String does not contain a space");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜