Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the preview date in preview mode to show date-specific content in Sitecore?

Tags:

sitecore

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.

like image 461
Ed Schwehm Avatar asked Mar 24 '23 00:03

Ed Schwehm


2 Answers

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.

like image 105
Ed Schwehm Avatar answered Apr 06 '23 05:04

Ed Schwehm


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.

like image 37
Mark Ursino Avatar answered Apr 06 '23 06:04

Mark Ursino