-1

I am working on a multilingual formular and have to solve a date formatting problem:

In German the date format is: DD-MM-YYYY While in another country e.g. England the date format is: YYYY-MM-DD

While this input validation is handled right, I need to get a easy solution for my php script to handle different date formats. In my MySQL-Database the field is created as a "date" field.

I already thought about a function like this:

<? 
if($lang == "de") {
   $date = $_POST['date'];
   $toConvert = DateTime::createFromFormat('d-m-Y', $date);
   $convertedDate = $toConvert->format('Y-m-d');
}

But isn't there a simpler solution as checking all countries with a different time format than Y-m-d? Maybe a library or something? I haven't found anyhting ..

Best regards DB-Dzine

  • What do you think the library is gonna do? It's gonna have a switch statement or a bunch of if/else statements just like you would. – John Conde Jun 22 '15 at 15:02
  • Maybe Carbon can help you: https://github.com/briannesbitt/Carbon – Daan Jun 22 '15 at 15:03
  • there's always just `strtotime($date)`, which would be the software equivalent of playing pin-the-tail-on-the-donkey. of course, that's highly unreliable, especially on ambiguous inputs. – Marc B Jun 22 '15 at 15:06
  • Some countries may also use both YMD and DMY. How are you going to know what format the date comes in? What's your input source? You can't simply deduct it from the string, e.g. the string 10101112 could be 1010-Nov-12 (YMD), or 1010-11-Dec (YDM), or Oct-10-1112 (MDY). A bit less ambiguous if we're only talking 1900-present, but it's still ambiguous, e.g. 20112010 could be either YDM or DMY. – Markus AO Jun 22 '15 at 15:39

1 Answers1

0

I know that Zend has some of this logic in there zend_date (requires Zend Framework ^^), but I would just use a simple solution like this: (where you get the format from a switch statement)

 $date = $_POST['date'];
 $toConvert = DateTime::createFromFormat('d-m-Y', $date);

 switch($lang){
    case 'de': 
       $format = 'Y-m-d'; 
       break;
    default: 
       $format = 'd-m-Y'; 
       break 
 }

 $convertedDate = $toConvert->format($format);

By doing it by yourself, you know that the format you get is the right one (by your standard, and that isn't destroying something in your application)

  • Thank you for your comment. As I am working with the validation-engine from jquery (https://github.com/posabsolute/jQuery-Validation-Engine) I will check the language specific correct date-inputs and validate them then. – Daniel Barenkamp Jun 23 '15 at 06:16