[英]c# time format weirdness
I have the following string TheTimeFormat as the custom time format: 我将以下字符串TheTimeFormat作为自定义时间格式:
"{0:h:mm tt}"
I have the following DateTime TheTime: 我有以下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}
" . 为什么ThisTime等于“
{0:2:19 AM}
”。 It should be 2:19 AM and I'm not seeing why. 应该是2:19 AM,我不知道为什么。 Not that in a gridview, I use the following statement and it works like a charm:
并不是在gridview中,我使用以下语句,它的工作原理就像一个魅力:
((BoundField)(MyGrid.Columns[0])).DataFormatString = TheUserPreferences.UserTimeFormat
; ((BoundField)(MyGrid.Columns[0])).DataFormatString = TheUserPreferences.UserTimeFormat
; where TheUserPreferences.UserTimeFormat is the same format string. 其中TheUserPreferences.UserTimeFormat是相同的格式字符串。
Any suggestions? 有什么建议么?
When you put a time format into DateTime
's ToString
method, you don't need the placeholder; 将时间格式放入
DateTime
的ToString
方法中时,不需要占位符; 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): 根据注释中的扩展问题,这将使您可以将格式放入需要占位符的位置(并将上述版本的TheTimeFormat存储在db中):
string formatWithPlaceholder = "{0:" + TheTimeFormat + "}"; 字符串formatWithPlaceholder =“ {0:” + TheTimeFormat +“}”;
I just briefly played around with string.Format
instead of concatentation, but having the braces in the format is giving issues. 我只是简单地玩过
string.Format
而不是concatentation,但是在格式中使用花括号会带来问题。 Nonetheless, this works, but I don't particularly like the concatenation. 尽管如此,这仍然有效,但是我并不特别喜欢串联。
Change TheTimeFormat
to simply "0:h:mm tt"
. 将
TheTimeFormat
更改为简单的"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. 当您使用格式:您只需要在“{YYY X}”
String.Format()
或其他方法,如Console.WriteLine()
使用String.Format()
内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.