Sitecore Context Languages and Date Displays
Posted 10/14/2016 by Ed Kapuscinski
I'm generally pretty happy with the way that Sitecore handles multi-lingual sites, especially in Sitecore 8 where language fallback is an out of the box feature. There's one thing, though, that it doesn't do natively: set the CultureInfo for dates when a visitor is browsing a site in a certain language.
Here's the cheat sheet on how to deal with that.
First, let me explain the problem. Multi-lingual sites are often cross-cultural as well. This means that the site being displayed for someone in the US should look slightly different for someone browsing it in England, specifically when it comes to dates (and other numbers).
In the .NET world we often use shortcuts to output dates like ToShortDateString(). In the Sitecore world, we'd expect that somehow the implementation of that method would take the context culture (as defined by the context language variant) into account. It doesn't.
I know there are likely good and important reasons it doesn't, but it's still annoying!
So, when handling dates in a multi-cultural site, you need to go a little further to make sure your dates are being displayed as a visitor would expect.
To do this properly we need to grab the dateFormat from the context CultureInfo and then use it when formatting dates.
Here's all the code you need:
System.Globalization.CultureInfo contextCultureInfo = Sitecore.Context.Language.CultureInfo;
string dateFormat = contextCultureInfo.DateTimeFormat.ShortDatePattern;
string formattedDate = date.ToString(dateFormat);
I had googled this before and didn't come up with anything handy so I figured I'd write it up so I can find it next time I do it; hopefully to help my fellow Sitecore travelers.