Looking at the DateTimeFormatInfo documentation, it appears that all the standard formats have colons in them, which makes passing them on a url unpleasant/impossible.
Try HttpServerUtility.HtmlEncode and HttpServerUtility.HtmlDecode
If you need the date and time, I would use DateTime.Ticks.
If you only need the date, use HttpServerUtility.UrlEncode(date.ToShortDateString()).
Update: Rick Strahl has discussed this issue before and has offered a solution on his blog.
I'll put everything together into one answer:
You could do something like this:
string urlSafeDateString = HttpServerUtility.UrlTokenEncode(date.ToUniversalTime().ToString(System.Globalization.CultureInfo.InvariantCulture).ToCharArray());
DateTime date = DateTime.Parse(new string(HttpServerUtility.UrlTokenDecode(urlSafeDateString)), System.Globalization.CultureInfo.InvariantCulture).ToLocalTime();
Or you could do something like this:
string urlSafeDateString = date.ToUniversalTime().ToString("yyyyMMddTHHmmss", System.Globalization.CultureInfo.InvariantCulture);
DateTime date = DateTime.ParseExact(urlSafeDateString, "yyyyMMddTHHmmss", System.Globalization.CultureInfo.InvariantCulture).ToLocalTime();
I've just come across this same problem and solved it with the following helper method:
private string Encode(DateTime date)
{
var formattedDate = date.ToString("yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
return WebUtility.UrlEncode(formattedDate);
}
After using the output in a URL query parameter the value gets correctly deserialised by .NET into DateTime objects passed into my Web API Service.
We actually have a reporting solution where dates and times can be passed in as plain text CCYYMMDD
and hhmmss
values then, when the code needs to do anything to those values, it simply uses string operations to turn them back into a format that can be displayed or easily parsed (such as the DB2 ISO formats CCYY-MM-DD or hh.mm.ss).
The result is readable and I'd be surprised if .NET didn't have string manipulation instructions that could do this easily.
For what it's worth, ASP.NET MVC won't automatically convert ticks to a datetime either, which surprised me.
There's a constructor for DateTime that takes the number of ticks:
DateTime d = new DateTime(634028202671420663);
There's also an override that lets you map that to either local or UTC time. It's all in the docs: http://msdn.microsoft.com/en-us/library/system.datetime.datetime.aspx
Edit: realised from the wording of the post that perhaps you're talking about ASP converting the ticks automatically to a DateTime, rather than having to read the numeric parameter. Perhaps! :-)