开发者

c# time format weirdness

I have the following string TheTimeFormat as the custom time format:

  "{0:h:mm tt}"

I have the following DateTime TheTime:

  {1/14/2011 2:19:00 AM}

I have the following statement

  ThisTime = TheTime.ToString(TheTimeFormat);

Why is ThisTime equal to "{0:2:19 AM}" . It should be 2:19 AM and I'm not seeing why. Not that in a gridview, I use the foll开发者_如何学Goowing statement and it works like a charm:

((BoundField)(MyGrid.Columns[0])).DataFormatString = TheUserPreferences.UserTimeFormat; where TheUserPreferences.UserTimeFormat is the same format string.

Any suggestions?


When you put a time format into DateTime's ToString method, you don't need the placeholder; that is, you could have this:

TheTimeFormat = "h:mm tt";

and

ThisTime = TheTime.ToString(TheTimeFormat)

would give you the desired output.

EDIT:

Per the extended question in the comment, this would allow you to put your format in something that requires a placeholder (and store the aforementioned version of TheTimeFormat in the db):

string formatWithPlaceholder = "{0:" + TheTimeFormat + "}";

I just briefly played around with string.Format instead of concatentation, but having the braces in the format is giving issues. Nonetheless, this works, but I don't particularly like the concatenation.


Change TheTimeFormat to simply "0:h:mm tt".

You only need the "{X:YYY}" format when you are using String.Format() or the other methods like Console.WriteLine() that use String.Format() internally.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜