Welcome Guest! Login? Checkout

Recently I had a problem with CMB2 and date fields. We were using an API that had dates stored in EU format (which is day/month/year), but try as we might we couldn’t get CMB2 to import the dates correctly. Many of the dates were in US format (month/day/year) and a few never even imported successfully. After a fair bit of tinkering, we found the solution.

Change Date Format to Use EU Date Format

First of all, we need to make sure our datepicker field is using the correct format. CMB2 has a number of great hooks and filters that help with this. One such filter is cmb2_localized_data, which allows you to localise the fields and the data CMB2 uses.

This first step isn’t to look at imported data, but it is to make sure that data should you save it at a later date is of the right format – nothing can be more frustrating post import than making changes that affect your dates, so it’s a crucial step. The code below will localise this to EU date formats.

Paste that into a functions PHP file and that will allow you to save dates as EU format.

Importing Dates into CMB2 Fields

Now what eventually messed me up and what I had to correct was the date format, and how datepicker treats formatted dates. Although dates such as 31/10/2017 are classed as UK dates, it was the fact that the forward slash was in the date as the separator meant that the date picker thought it was a US date. EU separators are hyphens. So as a result we have to convert the string into a EU datestring, and then carry out a string to time check, so that way we get a more accurate timestamp, before importing it into CMB2.

And that’s it! Make sure your field is 'type' => 'text_date_timestamp', so that it does work, but that should help you manage dates in CMB2.

 
 
 

Comments

Polite Disclaimer: I am welcome, open and willing for corrections to be shared in the comments (with corrections being added to posts and credited), and the comments field should be used to promote discussion and make this post better. I do not know everything and if anybody finds a better way to do something, then by all means please share it below.

However, I'm unable to offer support to posts. The reason being is that WordPress has tens of thousands of plugins and millions of themes. As such, finding out exactly why code doesn't work with your setup is a long process. If you wish for me to look at your code, please use the priority support area.

Comments asking support will be left on the site, but there is no guarantee of answer.

    Leave a Reply

    Your email address will not be published.

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">
    *