We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Improve your Craft CMS skills

Understand the Date Fields in Craft CMS

10 min read
Andy Golpys Made By Shape Founder

Handling dates properly is critical for any content site, yet date fields in CMS platforms remain shrouded in mystery. This article illuminates effective date use in Craft CMS, from modeling content and structuring databases to displaying dates intuitively on the front-end. Whether you're a novice developer struggling to wrangle dates or a seasoned pro seeking deeper date mastery, these tips will save headaches and unlock the full power of dates in Craft.

Date fields enable powerful time-based content modeling. They structure entries chronologically, relate content by dates, and facilitate archives/calendars. Robust tools like element queries and Twig formatting provide flexible date handling. But invalid formats, timezone mismatches, and debugging woes can disrupt dates. With planning and precision, Craft’s dates unlock potent content organization.

Working with Dates in Craft CMS

Overview of Date Fields in Craft CMS

Date fields are an essential component of Craft CMS that enable you to easily manage date-based content. They allow you to set dates for scheduling content publication, event dates, expiring promotions, and more.

Some common uses of date fields in Craft include:

  • Scheduling content - You can set a Post Date field and use it to schedule when entries should be published in the future or expire in the past. This is useful for blogs, news content, and events.

  • Event management - Events plugins like Craft Event Manager leverage date fields to capture event dates, registration deadlines, venues, and other date-relevant info. This helps manage real-world events.

  • Promotions - Date fields come in handy for setting start and end dates for promotions, sales campaigns, and other time-sensitive content.

The date picker UI makes it easy for content editors to choose dates and times without needing to manually enter them. Overall, date fields provide a flexible way to structure date-driven content in Craft CMS.

Importance of Date Data in CMS

Proper date handling is crucial in any CMS because dates enable so much of the structured content that systems like Craft are built on. Here are some key reasons date data matters:

  • Content modeling - Dates are integral to content modeling in a CMS. For example, blog posts are often modeled around a publication date field. This structures content chronologically.

  • Archives - Date fields power site archives that list content by year, month, day etc. Readers rely on archives to navigate back in time.

  • Calendars - Events, concerts, conferences and more are inherently calendar-based. Date fields make it possible to output CMS content in calendar views.

  • Timeliness - Dates allow content to be published, expire or enter draft status based on time. This keeps content timely and relevant.

  • SEO - Proper date schema improves SEO. Date fields output structured data that Google understands.

  • Reporting - Date information enables reports on metrics like most popular times of year, best publication dates, etc.

In summary, dates are a foundational content type in CMS platforms. They enable chronological structuring, archiving, calendars and time-based experiences vital to managing content. Robust date handling unlocks many possibilities.

Working with the Native Date Field in Craft CMS

Date Field Type and Format

The built-in Date field in Craft CMS enables you to capture and store date and time values. Under the hood, it uses the PHP DateTime object to handle dates.

Dates are stored in the standard YYYY-MM-DD HH:MM:SS datetime format along with the timezone. So a date might be stored as 2022-12-15 14:30:00 Europe/London for example.

This datetime storage format enables easy sorting, comparison and calculation of dates in Twig templates. The timezone is necessary since dates and times are relative and locale-specific.

When entering dates in the control panel, the date picker allows choosing the date and time conveniently. The stored datetime format also ensures consistency across regions since everyone’s date values are normalized to the same structure behind the scenes.

Configuring Date Field Settings

The Date field in Craft has several useful settings to control date entry and display:

  • Default Value - Sets a default date pre-populated on new entries. Useful for posts defaulting to the current date.

  • Min/Max Value - Restricts dates entered to a minimum and maximum. Helps prevent illogical or expired dates.

  • Display Format - Customizes how stored dates are formatted for front-end display via Twig formatting tags.

  • Timepicker Options - Determines whether to show time selection alongside dates in the picker.

These settings adapt the field to specific use cases. For events, the min/max dates may span months but for news content it’s likely just days or weeks. The display format can be tailored to style dates exactly how you need.

Overall, the Date field settings provide flexibility while retaining the standard datetime storage format required for robust dates in a CMS.

Working with Dates in Twig

Twig makes it easy to work with dates from Date fields in templates:

  • Format dates for display with {{ post.date | date() }} using tokens like d/m/Y.

  • Compare dates using operators like {post.date > today} to check if it's a future date.

  • Calculate dates like {post.date|date_modify('+1 week')} to get dates relative to stored values.

  • Access date attributes like {post.date|date('Y')} to get the year for archiving.

  • Store formatted dates in new variables like {set formattedDate = post.date|date('F Y')} for re-use.

Twig date functions like |date(), |date_modify() and {now} handle the logic behind the scenes. And variables store re-usable date values. This makes working with dates in Twig templates a breeze.

Displaying and Outputting Dates in Craft CMS

Formatting Dates

When displaying dates from Craft CMS to end users, proper formatting is important for localization and legibility.

Craft's |date() filter handles default date formatting. You can pass in a date string like 'd/m/Y' to format dates as "15/11/2022" for UK sites. Or 'm/d/Y' for US formatting.

For times, using 'h:i a' displays "3:30 pm" with am/pm. And 'H:i' is "15:30" 24-hour time.

These formatting options localize dates automatically. Craft sends the right format for the target locale. So UK and US sites get their own date styles without extra work.

Some examples:

{{ post.postDate | date('d F Y') }} -> 15 November 2022

{{ event.startDate | date('D, d M Y') }} -> Mon, 7 Nov 2022

{{ product.saleEnds | date('m/d/Y') }} -> 11/20/2022

The flexibility handles any regional date/time requirements.

Date Display Control

Beyond formatting, Craft also offers settings to control date output:

  • Show only certain date parts like year, month or day.

  • Set the timezone used for display dates.

  • Configure localization like month names in French.

  • Choose which date fields display where, like on blog index vs detail templates.

This gives granular control over front-end date views. For example, you may only show the year on archive pages but full dates on detail templates.

Display settings bridge the gap between stored datetime formats and user-friendly views.

Front-end Date Customization

For deeper front-end date customization, JavaScript libraries like Moment.js help craft completely custom date views.

Moment.js can format dates in any way like:

moment(post.date).format('MMMM Do YYYY'); -> November 11th 2022

moment(event.startDate).fromNow(); -> 3 days ago

This bypasses Craft's formatting to create dynamic formatted dates on demand.

Use cases include custom relative date strings ("3 days ago"), ordinal date suffixes ("November 19th"), aggregated views ("September 2022") and more.

Moment.js integrates date superpowers for unique UX needs. And Craft's datetime field values offer the data to fuel it all.

The possibilities are endless for date experiences users will love.

Working with Date Ranges in Craft CMS

Overview of Date Ranges

Date ranges in Craft CMS allow querying for entries between two dates. This powers date-based content selection in calendars, archives, and more.

For example, you can fetch blog posts between '2022-01-01' and '2022-02-28' to output the articles for February 2022. Or find events between today and a year from now to display upcoming occurrences.

Date ranges pass the start and end dates to Craft's element query APIs. It then selects all entries with date field values falling within those dates.

This provides an easy way to slice content by date without manual filtering logic in Twig. And the familiar date picker UI makes choosing start/end points simple for editors.

Date Range Query Examples

Fetching elements by a date range in Craft is straightforward:

{% set start = '2022-12-01' %}

{% set end = '2023-01-31' %}

{% set entries = craft.entries()

.postDate(['and', '>= ' ~ start, '<= ' ~ end])

.all() %}

This finds entries between Dec 1, 2022 and Jan 31, 2023. The 'postDate' logic can be tweaked to match your date fields.

Other examples:

{# Fetch upcoming events #}

{% set nextMonth = now|date_modify('first day of next month')|date('Y-m-d') %}

{% set events = craft.entries()

.eventDate(['and', '>= ' ~ now, '< ' ~ nextMonth])

.all() %}

{# List articles by year #}

{% set year = craft.app.request.getParam('year') %}

{% set posts = craft.entries()

.postDate(['and', '>= ' ~ year ~ '-01-01', '< ' ~ year ~ '-12-31'])

.all() %}

TheCraft element query API handles the heavy lifting.

Use Cases for Date Ranges

Date ranges enable several common use cases:

  • Archives - Fetch entries by year/month for archives.

  • Calendars - Populate calendar views with entries in date range cells.

  • Schedules - Show upcoming events within a date range.

  • Recent content - Get articles published in the last 30 days.

  • Expiring content - Remove expired promotions between set dates.

  • Birthdays - List people with birthdays this month.

  • Trends - Analyze metrics by date like weekly sales or signups.

Date ranges are a powerful tool for organizing, displaying, and filtering date-based content in Craft CMS.

Content Modeling with Date Fields in Craft

Benefits for Content Modeling

Dates provide immense benefits for content modeling in Craft CMS. By adding date fields to entries, you can structure content chronologically in an intuitive way that mirrors real-world timelines. Date values enable creating logical connections between related content over time, such as entries in a blog series or events tied to specific dates. Dates also facilitate automatic segmentation of content into archives organized by year, month, day etc.

This kind of structured organization happens seamlessly behind the scenes based on date field values, removing the need for complex manual coding. Overall, date fields bring time-based intelligence to content modeling, supporting more meaningful relationships between content elements and smarter archival systems.

Date Field Relations

Date fields relate and connect various content types together through shared date values. For example, entry dates can sequence articles into a continuous blog series based on chronology.

Or they can cross-reference entries like linking products to blog posts about them published on the same day. You can also associate entries with categories by time segments such as year or month for intuitive organization. Even relating entries to authors based on contribution dates provides more robust content modeling capabilities. The common thread here is utilizing dates to create deeper relationships and bridges between content elements of all kinds. Date fields enable any content types to become interconnected based on chronology.

Structuring Entry Content

Date values provide a powerful approach to structuring entry content for outputs and displays. For example, entry dates can automatically split content into year and month segments for archive indexes and calendars filtered to only show content in certain date ranges. Granular date modeling with fields for day of week or publication hour introduces even more possibilities for sorting content by specific recurrent time units. You can also structure content by relative date ranges like displaying only entries from the last 30 days or future content arriving in the next 3 months.

By leveraging native date tools like element queries in Craft, no additional plugins are required to sub-divide content by dates. For instance, an archive page could output entries grouped by month of the year using Twig code that filters entries by their date field value. The content modeling potential unlocked by dates is nearly limitless. Any content structure based on chronology can be modeled using Craft's robust date capabilities.

Troubleshooting Common Date Issues in Craft

Invalid Dates

Invalid dates like 'February 30th' can occur due to formatting mismatches between data entry and storage formats.

Craft alerts editors if an invalid date is entered through the CP. But bad data could still get through via imports.

To prevent issues:

  • Choose date formats that avoid ambiguity - like YYYY-MM-DD.

  • Validate dates before import with helpers like PHP's checkdate()

  • Use Craft's default date formatting where possible.

  • Add validation rules to dates like requiring four-digit years.

To fix invalid existing dates:

  • Resave the date through the CP to normalize the format.

  • Adjust date formats to match the database.

  • For imports, sanitize dates into a valid datetime string first.

With some care around input and validation, bad date data can be avoided.

Timezone Mismatches

Timezones can cause issues when the timezone saving a date differs from the one displaying it. For example, an event created in London at 8 PM would show 1 PM in New York.

To avoid this:

  • Set an application-wide default timezone for date handling.

  • Store timezone info alongside dates.

  • Normalize dates to UTC and convert for output.

  • Offset displayed dates by the timezone delta.

  • Dynamically localize dates on the front-end.

With a consistent timezone strategy, you can build localized date experiences.

Debugging Date Problems

For other date problems, debug with validation and logging:

  • Check date format - Is it valid for the field type?

  • Log values before and after processing.

  • Inspect date parameters passed to queries.

  • Confirm date comparisons use proper operands.

  • Print parsed dates after Twig formatting.

  • Enable Craft debug toolbar to diagnose request issues.

  • Break code into smaller blocks to isolate bugs.

  • Test edge cases like leap years.

Dates can certainly misbehave but validation diligence, logging and precision debugging will tame them.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat