Format Sitecore Date using Sitecore().Field()?
Asked Answered
H

4

5

I need to use a custom format for a date (i.e. dddd dd MMMM yyyy). Is it possible to pass this format to Sitecore().Field()? I would like to do something like this:

@Html.Sitecore().Field("Day1", new { @format="dddd dd MMMM yyyy"})

However, after some Googling, I found that I either have to create a custom field helper to do this or a custom model. Is there really no way to do this using base Sitecore? It's important this be done through Sitecore().Field() as I need the content editor to be able to edit the value.

We're on Sitecore 7.5

Hum answered 25/12, 2015 at 22:42 Comment(2)
I think it has been introduced in later versions because this works fine for me in SXP8.2 @Html.Sitecore().Field("Start Date", new { format = "dd MMMM yyyy" })Flagler
I remember this being an option while attending the Sitecore developer elearning. Module 4 if I am not mistaken. The course is Sitecore 8.Indices
F
4

As far I know Sitecore doesn't have such a functionality out of the box. You can use a helper for this functionality, please check below code. I used this code and is working fine. You can edit date field also from page editor because the field is edited through Sitecore pipelines.

public static class Helper
{

    public static HtmlString RenderField(
      this SC.Mvc.Helpers.SitecoreHelper sitecoreHelper,
      string fieldNameOrId,
      bool disableWebEdit = false,
      SC.Collections.SafeDictionary<string> parameters = null)
    {
        if (parameters == null)
        {
            parameters = new SC.Collections.SafeDictionary<string>();
        }

        return sitecoreHelper.Field(
          fieldNameOrId,
          new
            {
                DisableWebEdit = disableWebEdit,
                Parameters = parameters
            });
    }

    public static HtmlString RenderField(
      this SC.Mvc.Helpers.SitecoreHelper sitecoreHelper,
      SC.Data.ID fieldId,
      bool disableWebEdit = false,
      SC.Collections.SafeDictionary<string> parameters = null)
    {
        return RenderField(
          sitecoreHelper,
          fieldId.ToString(),
          disableWebEdit,
          parameters);
    }

    public static HtmlString RenderDate(
      this SC.Mvc.Helpers.SitecoreHelper sitecoreHelper,
      string fieldNameOrId,
      string format = "D",
      bool disableWebEdit = false,
      bool setCulture = true,
      SC.Collections.SafeDictionary<string> parameters = null)
    {
        if (setCulture)
        {
            Thread.CurrentThread.CurrentUICulture =
              new CultureInfo(SC.Context.Language.Name);
            Thread.CurrentThread.CurrentCulture =
              CultureInfo.CreateSpecificCulture(SC.Context.Language.Name);
        }

        if (parameters == null)
        {
            parameters = new SC.Collections.SafeDictionary<string>();
        }

        parameters["format"] = format;
        return RenderField(
          sitecoreHelper,
          fieldNameOrId,
          disableWebEdit,
          parameters);
    }

    public static HtmlString RenderDate(
      this SC.Mvc.Helpers.SitecoreHelper sitecoreHelper,
      SC.Data.ID fieldId,
      string format = "D",
      bool disableWebEdit = false,
      bool setCulture = true,
      SC.Collections.SafeDictionary<string> parameters = null)
    {
        return RenderDate(
          sitecoreHelper,
          fieldId.ToString(),
          format,
          disableWebEdit,
          setCulture,
          parameters);
    }

    public static HtmlString TagField(
      this SC.Mvc.Helpers.SitecoreHelper sitecoreHelper,
      string fieldNameOrId,
      string htmlElement,
      bool disableWebEdit = false,
      SC.Collections.SafeDictionary<string> parameters = null)
    {
        SC.Data.Items.Item item =
          SC.Mvc.Presentation.RenderingContext.Current.ContextItem;

        if (item == null || String.IsNullOrEmpty(item[fieldNameOrId]))
        {
            return new HtmlString(String.Empty);
        }

        string value = sitecoreHelper.RenderField(
          fieldNameOrId,
          disableWebEdit,
          parameters).ToString();
        return new HtmlString(String.Format(
          "<{0}>{1}</{0}>",
          htmlElement,
          value));
    }

    public static HtmlString TagField(
      this SC.Mvc.Helpers.SitecoreHelper sitecoreHelper,
      SC.Data.ID fieldId,
      string htmlElement,
      bool disableWebEdit = false,
      SC.Collections.SafeDictionary<string> parameters = null)
    {
        return TagField(
          sitecoreHelper,
          fieldId.ToString(),
          htmlElement,
          disableWebEdit,
          parameters);
    }
}

In your cshtml you will have:

       @Html.Sitecore().RenderDate("Name of field or id", "your format")

John West write about how to extend sitecore helpers here: http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2012/06/sitecore-mvc-playground-part-4-extending-the-sitecorehelper-class.aspx

Fidge answered 26/12, 2015 at 6:43 Comment(5)
Thanks, that works. Also, I just want to confirm that the TagField methods aren't needed for anything related to my original question, correct?Hum
@MrSnappingTurtle you are right tagfield is not used. If the answer is correct please mark it correct. Others will use this response in the future.Fidge
@SitecoreClimber, I have used but modified your code, since I needed to use it for children of current context item. Modified answer below.Wuhsien
Ok but why you give other anwer? :)Fidge
I do not think this is necessary in Sitecore 8Indices
P
4

You can format date using below Field render syntax which is easy and out of the box.

@Html.Sitecore().Field("Date Field", new {format="MMM dd, yyyy"})

That's it. The format value leveraged the standard date format specifications.

Progestational answered 22/2, 2019 at 16:57 Comment(0)
H
2

For those who had an issue while dealing with spaces, simply replace all the spaces with "\n".

An example here:

@Html.Sitecore().Field(datefield, new {format="MMM\ndd,\nyyyy"})
Hollenbeck answered 17/3, 2020 at 9:41 Comment(0)
W
0

I have modified @SitecoreClimber answer, because it doesn't work for rendering children items since it uses default RenderingContext.Current

So I have updated every method arguments and added Item item and used that item for base field rendering, like this:

    public static HtmlString RenderField(this SitecoreHelper sitecoreHelper, string fieldNameOrId, Item item, bool disableWebEdit = false, SafeDictionary<string> parameters = null)
    {
        if (parameters == null)
        {
            parameters = new SafeDictionary<string>();
        }

        return sitecoreHelper.Field(fieldNameOrId, item,
            new
            {
                DisableWebEdit = disableWebEdit,
                Parameters = parameters
            });
    }

So in my MVC view I can now have:

@foreach (Item item in @Model.Item.Children)
{
    <div class="event-date">
        @Html.Sitecore().RenderDate("Date", item, "d MMM")
    </div>
}
Wuhsien answered 25/2, 2016 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.