Friday, August 31, 2007

What is good to know about SPUtility.FormatDate

Today, while developing a custom web part, I’ve decided that it would be handy to use SPUtility.FormatDate to format all dates, and avoid dealing with String.Format and CultureInfo. And it actually was! Except one small issue, it’s good to know about: SPUtility.FormatDate will not only format specified date according to regional settings used in specific web, but it also assumes that provided time is UTC one, and will convert it to local time of the web, analyzing it’s time zone.
So if you already have a local time, you should convert it to UTC first:

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

SPSite site = new SPSite("http://localhost");
SPWeb web = site.RootWeb;
DateTime dt = DateTime.Now;
string dateStr = SPUtility.FormatDate(web, web.RegionalSettings.TimeZone.LocalTimeToUTC(dt), SPDateFormat.DateTime);

1 comment: said...

Oh my god, there's a great deal of useful material in this post!