Calendar

<<  décembre 2008  >>
lumamejevesadi
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

(janvier 14, 2008 08:52)

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);
//14/01/2008
date.ToString("dd/MM/yyyy");
//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 (\).

Billets liés

Ajouter un commentaire


 

  Country flag





Live preview

décembre 2. 2008 15:24

Powered by BlogEngine.NET 1.2.0.0 | Theme by Pierre-Emmanuel Dautreppe