janv. 14

You all know the DateTime.ToString method I imagine. However I have had a little problem a few days ago, so let's it share with you !

You may all be aware of this behavior:

DateTime date = new DateTime(2008, 01, 14);
//To14a8 i0 14/01/2008
date.ToString("Today is dd/MM/yyyy");

Indeed in the pattern, the "d" will be interpreted as the day, "y" as the year and "s" as the seconds. So we need to protect them, enclosing the non-parasable characters using quotes. (Here enclosing the "/" is not mandatory, but I like to protect ALL my non parsable characters.

//Today is 14/01/2008
date.ToString("'Today is 'dd'/'MM'/'yyyy");

Now let's imagine your non parsable characters includes a quote.

//FormatException in both cases
date.ToString("Today, dd/MM/yyyy, I'm living in Brussels"); 
date.ToString("'Today, 'dd'/'MM'/'yyyy', I'm living in Brussels'");

You wil get a FormatException because your query includes an incorrect number of quotes (they should always work 2 by 2).  You imagine you need to protect this quote but how ? "Simply" by enclosing it with double-quotes. (Note that the exception message will be System.FormatException: Cannot find a matching quote character for the character '''.)

//Today, 14/01/2008, I'm living in Brussels
date.ToString("'Today, 'dd'/'MM'/'yyyy', I'\"'\"'m living in Brussels'");

This leads to a bit complex expression but it works !

Note that here, you find the expression '\"'\"'. The first quote (') is the closing quote of the previous text and the last one is the opening quote for the last text part. After you find two double quotes (") to protect the quote we want to write. As we are in a non-verbatim string, the double-quotes shall be protected using backslahes (\).

Tags: | | |


Ajouter un commentaire

  • Commentaire
  • Aperçu immédiat