简体   繁体   English

将DateTime.toString()传递给AppendFormat C#.NET时发生FormatException

[英]FormatException when passing DateTime.toString() to AppendFormat C# .NET

I'm trying to do the following: 我正在尝试执行以下操作:

 var policyBuilder = new StringBuilder();    

 var expiration = DateTime.UtcNow.AddDays(1).ToString("s") + "Z";

 policyBuilder.AppendFormat("{ \"expiration\": \"{0}\",\n", expiration);

However, the last line throws the following exception: 但是,最后一行抛出以下异常:

 An exception of type 'System.FormatException' occurred in mscorlib.dll 
 but was not handled in user code

 Additional information: Input string was not in a correct format.

'expiration' is a string, so why am I getting this error? 'expiration'是一个字符串,那么为什么会出现此错误?

Thanks 谢谢

If you want a { at the beginning you have to use two: 如果想在开始时使用{ ,则必须使用两个:

policyBuilder.AppendFormat("{{ \"expiration\": \"{0}\",\n", 10);

See: Escaping Braces in Composite Formatting 请参阅: 以复合格式转义大括号

Opening and closing braces are interpreted as starting and ending a format item. 左括号和右括号被解释为格式项的开始和结束。 Consequently, you must use an escape sequence to display a literal opening brace or closing brace. 因此,必须使用转义序列来显示文字的右括号或右括号。 Specify two opening braces ("{{") in the fixed text to display one opening brace ("{") , or two closing braces ("}}") to display one closing brace ("}"). 在固定文本中指定两个开括号(“ {{”)以显示一个开括号(“ {”) ,或两个闭括号(“}}”)以显示一个闭括号(“}”)。 Braces in a format item are interpreted sequentially in the order they are encountered. 格式项中的大括号将按其遇到的顺序顺序进行解释。 Interpreting nested braces is not supported. 不支持解释嵌套括号。 .... ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM