Problem when concatenating formatted string
currTime = DateTime.Now.ToString("u");
The code above first formats the time now to yyyy-mm-dd hh-mm-ss
(Alpha numerical).
I wanted to remove the alpha numerical character so I used
currTime = currTime.Substring(0, currTime.Length - 1);
I then added ".000" to the end using
currTime = currTime + ".000";
However, this then removes the formatting and when displayed shows the standard dd-mm-yyyy
format. So my question is in two parts:
So...
How do I format DateTime.Now
to yyyy-mm-dd hh:mm:ss
with开发者_如何转开发out the alpha numerical character?
And how to add ".000" without losing my format?
DateTime.Now.ToString(@"yyyy\-MM\-dd hh\-mm\-ss.000")
though are you sure you don't want DateTime.Now.ToString(@"yyyy\-MM\-dd hh\:mm\:ss.000")
?
I'm afraid I simply don't believe you. Simple string concatenation isn't going to start messing around with the rest of the string.
Here's a short but complete example showing it not changing:
using System;
class Test
{
static void Main()
{
string currTime = DateTime.Now.ToString("u");
currTime = currTime.Substring(0, currTime.Length - 1);
currTime = currTime + ".000";
Console.WriteLine(currTime);
}
}
Output:
2011-03-22 12:28:39.000
I don't think that's the best way of coming up with that format, but it certainly isn't behaving the way you claim. Can you come up with a similar short but complete program which backs up your assertion that "this then removes the formatting and display it as the standard dd-mm-yyyy format"? My guess is that you're not seeing what you actually think you're seeing, but without a complete program it's hard to tell what's really going on.
Something like this ought to do the trick, with the slight alteration that appends the actual fraction of seconds rather than a hard-coded .000
:
var result = string.Format("{0:yyyy-MM-dd hh:mm:ss.fff}", DateTime.Now);
精彩评论