简体   繁体   中英

Convert French date string to English date for comparison

I'm running a multi-lingual WordPress site and I need to compare a meta value from a custom post type to the current date.

In English, it's fairly straight forward as I compared the user-entered start_date with the system time like so:

$postStartDate = strtotime(get_field('start_date'));
$currDate = strtotime(date('F j, Y'));

if ($postStartDate > $currDate):
  // Show the post
endif;

I can't use the built-in Published date from WordPress because my client sets up posts far in advance and they should be live until the meta start_date is past.

When I try and run something similar with French, however, it fails and that's because strtotime() expects English. Fair. So, I read a bit about setlocale() and strftime() and ended up trying things like this:

$frenchDate = strftime("%d %b %Y", strtotime(get_field('start_date')));

Of course, this also fails because strtotime() cannot understand 'Janvier' versus 'January', etc. so it's a non-starter right away. strftime() just spits out Jan 1, 1970 in this case.

This isn't a French server environment, merely a bilingual site.

What is the best way to compare a French date string to the current system date?

The best solution I could come up with when the overall site architecture can't be changed was to create an associate array to map French strings back into English for strtotime() to understand:

var monthMap = {
  'janvier' => 'january',
  ...
}

Lowercase your strings then take the French month and replace it with substr_replace() to create an English date.

A little hacky? Yes. But in the absence of any other answers, it works (so long as all French months are spelled properly by the inputting user!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM