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

时间:2016-02-25 12:09:56

标签: c# .net

我试图执行以下操作:

 var policyBuilder = new StringBuilder();    

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

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

但是,最后一行抛出以下异常:

 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.

'到期'是一个字符串,为什么我会收到此错误?

由于

1 个答案:

答案 0 :(得分:1)

如果您想在开头使用col_date,则必须使用两个:

{

请参阅:Escaping Braces in Composite Formatting

  

打开和关闭括号被解释为开始和结束a   格式项。因此,您必须使用转义序列来显示   一个字面的开口支撑或关闭支撑。 指定两个开口大括号   (“{{”)在固定文本中显示一个左括号(“{”)或两个   关闭大括号(“}}”)以显示一个右大括号(“}”)。大括号   格式项按顺序依次解释   遇到。不支持解释嵌套大括号。 ....