Displaying Time

Displaying Time

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

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

Displaying Time C# Web Control Code

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

Sitecore.Data.Fields.DateField date = item.Fields["__updated"];
if (date == null) return;

System.DateTime datetime = Sitecore.DateUtil.IsoDateToDateTime(date.Value);
if (datetime == null) return;

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}", "Raw Datetime", "<b>" + date.Value + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "ISO Now Datetime", "<b>" + Sitecore.DateUtil.IsoNowTime + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "ISO Now Datetime with Ticks", "<b>" + Sitecore.DateUtil.IsoNowWithTicks + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "ISO __updated Time", "<b>" + Sitecore.DateUtil.ToIsoTime(datetime, false) + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "ISO __updated Time with Ticks", "<b>" + Sitecore.DateUtil.ToIsoTime(datetime, true) + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "Military Time Display", "<b>" + Sitecore.DateUtil.DateTimeToMilitary(datetime) + "</b>");

output.RenderEndTag(); //Div


Displaying Time C# Web Control Output

Raw Datetime: 20140824T074011:635444628113211279
ISO Now Datetime: 075227
ISO Now Datetime with Ticks: 20141006T075227:635481787478165879
ISO __updated Time: 074011
ISO __updated Time with Ticks: 074011:635444628113211279
Military Time Display: 24-AUG-2014 07:40:11

Notes

  • The system date value is from the time zone where the server is located

Sources