简体   繁体   中英

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?

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. ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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