Convert creation date UTC to local in view

Topics: Customizing Orchard, General
Jan 18, 2013 at 2:16 PM

I want to display the creation date of a content type in a view.

@Model.ContentItem.CommonPart.CreatedUtc is what I need but it's stored in UTC format.

The method Orchard.Core.Shapes.DateTimeShapes.ConvertToDisplayTime() can convert this to a local datetime.

However, I'm not sure how I can call this method. Should I instantiate the class and call the method? How? I've never worked with Castle before.

Jan 18, 2013 at 2:57 PM

By debugging through the source code, this is what I've got so far:

@Display.DateTime(DateTimeUtc: Model.ContentItem.CommonPart.CreatedUtc, CustomFormat: new Orchard.Localization.LocalizedString("dd-MM-yyyy"))

It goes through a lot of code to accomplish what I need. Parameters must be named, or it will fail. Is there a better way?

Jan 18, 2013 at 3:24 PM

This is somewhat simplified:

@Display.DateTime(DateTimeUtc: Model.ContentItem.CommonPart.CreatedUtc, CustomFormat: T("d"))

If you use this code a lot you could write an HTML helper.

Jan 18, 2013 at 7:23 PM

Thanks, Sipke!

I'd rather build a helper method that would return the converted datetime instead of a string. But since ConvertToDisplayTime() is private, I see no obvious way to do this. Any ideas?

Jan 20, 2013 at 9:12 AM

No problem!
I suppose you could copy over the part of the implementation of the ConvertToDisplayTime method to your own helper method.

Jan 21, 2013 at 11:58 AM

This is what I ended up with, maybe it can help someone sometime.

public static DateTime ConvertToDisplayTime(this HtmlHelper html, DateTime dateTimeUtc)
	var workContext = html.ViewContext.RequestContext.GetWorkContext();

	var timeZone = workContext.CurrentTimeZone;

	return TimeZoneInfo.ConvertTimeFromUtc(dateTimeUtc, timeZone);

public static MvcHtmlString ConvertToDisplayTime(this HtmlHelper html, DateTime dateTimeUtc, string format)
	var dateTimeDisplay = html.ConvertToDisplayTime(dateTimeUtc);

	return MvcHtmlString.Create(dateTimeDisplay.ToString(format));