Get Short Date

Get Short Date

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Context
  • Sitecore.Data.Items.Item
  • Sitecore.DateUtil
  • System.DateTime

Short Date C# Web Control Code

Sitecore.Data.Items.Item item = Sitecore.Context.Item;
if (item == null) return;

string[] shortDate = new string[5];
shortDate[0] = Sitecore.DateUtil.GetShortIsoDateTime(System.DateTime.Now);
shortDate[1] = Sitecore.DateUtil.GetShortIsoDateTime(System.DateTime.Now).Substring(0, 8);
shortDate[2] = Sitecore.DateUtil.GetShortIsoDateTime(System.DateTime.Now).Substring(2, 6);

string isoDate = Sitecore.DateUtil.ToIsoDate(System.DateTime.Now);
if (!string.IsNullOrEmpty(isoDate))
{
    shortDate[3] = Sitecore.DateUtil.FormatIsoDate(isoDate, "d");
    shortDate[4] = Sitecore.DateUtil.FormatIsoDate(isoDate, "MM/dd/yy");
}

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("C# Web Control Real-time Output");
output.RenderEndTag();

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
//using : for colon and   for space
output.Write("{0}: {1}", "Item", item.DisplayName);
output.RenderEndTag(); //P

output.Write("{0}&#58;&#160;{1}", "Full Short Date", "<b>" + shortDate[0] + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "Medium Short Date", "<b>" + shortDate[1] + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "Small Short Date", "<b>" + shortDate[2] + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "Formatted Short Date 1", "<b>" + shortDate[3] + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "Formatted Short Date 2", "<b>" + shortDate[4] + "</b>");

output.RenderEndTag(); //Div


Short Date C# Web Control Output

Full Short Date: 20141006075531
Medium Short Date: 20141006
Small Short Date: 141006
Formatted Short Date 1: 10/6/2014
Formatted Short Date 2: 10/06/14