In the site I'm working on, certain content only appears once a certain date is reached:
public bool IsActive
{
get { return System.DateTime.Now >= this.IssueDate.DateTime; }
}
I want to test this code using the preview mode functionality and the experience bar. However, System.DateTime.Now
always returns the real current date, regardless of preview mode. How do I write this so I can guarantee that the date set in the experience bar is respected, but while in normal mode the page still uses System.DateTime.Now
?
Sitecore version: 6.4.1 rev. 110720
Update: I can't use publishing restrictions because children of this item need to be published and visible before this item appears in the menu that is controlled by this logic.
Sitecore provides a pair of properties to aid in this situation:
bool Sitecore.Configuration.State.Previewing
DateTime Sitecore.Configuration.State.PreviewDate
The Sitecore.Configuration.State.Previewing
property is true if preview mode is on, false otherwise. The Sitecore.Configuration.State.PreviewDate
property returns the Sitecore.Sites.SiteContext.DisplayDate
, which is set to the date in the experience bar in preview mode.
Here is the code I ended up using:
public bool IsActive
{
get
{
DateTime dateToUse;
if (Sitecore.Configuration.State.Previewing)
{
dateToUse = Sitecore.Configuration.State.PreviewDate;
}
else
{
dateToUse = DateTime.Now;
}
return dateToUse >= this.IssueDate.DateTime;
}
}
It appears to work fine without side effects.
The best approach to handle something like this is instead to restrict content from being published until a certain date.
In the content editor, on the Publish tab, click the Restrictions button to restrict when content can be published.
If you need content to go live at a certain date and time, you can leverage the Automated Publisher module for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With