I've a string '12/10/2010 00:00:00' I need to show this as ''12/10/2010' using c#. Help appreciated
+7
A:
You might try:
EDIT:
DateTime d;
DateTime.TryParse("12/10/2010 00:00:00", d);
d.ToString("MM/dd/yyyy");
Joel Etherton
2010-10-29 12:36:13
-1, I think you should check your code. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
Codesleuth
2010-10-29 12:38:42
@Codesleuth - Tru dat. Hasty code typing early in the morning. Thanx.
Joel Etherton
2010-10-29 12:40:14
Cool, removed the downvote :)
Codesleuth
2010-10-30 10:43:03
+6
A:
This takes the first half of your string before the space:
string formatedDt = "12/10/2010 00:00:00".Split(' ')[0];
Steve Danner
2010-10-29 12:37:12
Doesn't compile since string.Split is a member method and not a static function.
CodeInChaos
2010-10-29 13:07:10
I think this one doesn't work if the string contains no spaces at all.
CodeInChaos
2010-10-29 12:40:08
@CodeInChaos - none of these solutions work if there is no space. Why is this answer different?
Joel Etherton
2010-10-29 12:43:26
String.Split returns the whole string as [0] if the input string doesn't contain one of the split-chars.
CodeInChaos
2010-10-29 13:08:01
@CodeInChaos - I took the question "How to remove trailing spaces after a blank space, c#" to mean that there would always be at least one space.
scott
2010-10-29 13:17:49
@Scott, I think your answer is perfectly reasonable for the question asked. In the general case, though, it's important to note that if there isn't a space in the given string, Substring will throw an ArgumentOutOfRangeException since IndexOf will return -1. For the sake of promoting safe code, I think it's at least a good idea to check the return from the IndexOf before calling Substring.
Dave McClelland
2010-10-29 13:38:43
A:
"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");
}
CodeInChaos
2010-10-29 13:05:43
If there is no space, the returned string is "12/10/201000:00:00" which is not what OP wants.
Joel Etherton
2010-10-29 13:07:40
It's unclear what the OP want. Both returning the whole string and thus making the operation idempotent and throwing a descriptive exception seem reasonable to me. Throwing an ArgumentOutOfRangeException exception on the other hand doesn't seem reasonable to me.
CodeInChaos
2010-10-29 13:19:43
+6
A:
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:
Tergiver
2010-10-29 13:12:33